Skip to content

Commit

Permalink
update circular
Browse files Browse the repository at this point in the history
  • Loading branch information
dowell2020 committed Feb 27, 2022
1 parent 46cc4f2 commit 3637069
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 0 deletions.
55 changes: 55 additions & 0 deletions link/circular.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package link

import (
"errors"
"fmt"
)

type CirLink struct {
Val interface{}
Next *CirLink
}

func NewCirLink() *CirLink {
return &CirLink{}
}

// 插入值
func (c *CirLink) AppendCirLink(data interface{}) {
if c.Next == nil {
c.Next = &CirLink{data, c}
return
}
node := c.Next
if node.Next.Val == nil {
node.Next = &CirLink{data, node.Next}
return
}
c.Next.AppendCirLink(data)
}

// 删除值

func (c *CirLink) DeleteCirLink(data interface{}) error {
node := c.Next
if node.Val == data {
c.Next = node.Next
return nil
}
if node.Next.Val == nil {
err := errors.New("未找到对应值")
return err
}
c.Next.DeleteCirLink(data)
return nil
}

// 遍历数值

func (c *CirLink) TraversalCirLink() {
node := c.Next
fmt.Printf("遍历信息为:val=%d\n", node.Val)
if node.Next.Val != nil {
node.TraversalCirLink()
}
}
19 changes: 19 additions & 0 deletions link/circular_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package link

import (
"testing"
)

func TestCirCular(t *testing.T) {
clink := NewCirLink()
// 5,7,10,13,100,3000
clink.AppendCirLink(5)
clink.AppendCirLink(7)
clink.AppendCirLink(10)
clink.AppendCirLink(13)
clink.AppendCirLink(100)
clink.AppendCirLink(3000)
clink.TraversalCirLink()
clink.DeleteCirLink(13)
clink.TraversalCirLink()
}
17 changes: 17 additions & 0 deletions link/leet142.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package link

func detectCycle(head *ListNode) *ListNode {
// 判断只有第一个值的时候
if head == nil || head.Next == nil {
return nil
}
// 循环1
node := head
for node.Next != nil {
if node.Next == head {
// 证明是个环
return head
}
}
return detectCycle(head.Next)
}
18 changes: 18 additions & 0 deletions link/leet142_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package link

import (
"fmt"
"testing"
)

func TestDetectCycle(t *testing.T) {
// 例子3
node := NewListNode(1)
res := detectCycle(node)
fmt.Println(res)
// 例子2
node.addNode(2)
node.Next = node
res = detectCycle(node)
fmt.Println(res)
}

0 comments on commit 3637069

Please sign in to comment.