Skip to content

Commit 5e411ce

Browse files
committed
linkedlist refactor
1 parent ad8abdc commit 5e411ce

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

06-链表相关高频题总结.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,48 @@
3131

3232
> 1 3 5 2 7 返回 3;1 3 2 7 返回 3
3333
34+
```Go
35+
package main
36+
37+
type Node struct {
38+
Val int
39+
Next *Node
40+
}
41+
42+
// NewLinkedList 初始化一个链表 返回链表的头结点
43+
func NewLinkedList(val int) (head *Node) {
44+
return &Node{
45+
Val: val,
46+
Next: nil,
47+
}
48+
}
49+
50+
// MidOrUpMidNode 给定一个链表的头节点
51+
// 1. 奇数长度返回中点
52+
// 2. 偶数长度返回上中点
53+
func (head *Node) MidOrUpMidNode() *Node {
54+
// 该链表没有点,有一个点,有两个点的时候都是返回头结点
55+
if head==nil || head.Next == nil || head.Next.Next == nil {
56+
return head
57+
}
58+
59+
// 链表有3个点或以上
60+
// 快慢指针,快指针一次走两步,慢指针一次走一步
61+
// 快指针走完,慢指针在中点位置
62+
slow := head.Next
63+
fast := head.Next.Next
64+
for fast.Next != nil && fast.Next.Next != nil {
65+
slow = slow.Next
66+
fast = fast.Next.Next
67+
}
68+
return slow
69+
}
70+
```
71+
72+
73+
74+
75+
3476
```Java
3577
package class06;
3678

0 commit comments

Comments
 (0)