-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomm.go
64 lines (58 loc) · 1.05 KB
/
comm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package twopointer
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
// 验证回文性
func checkPalindrome(s string, left, right int) bool {
for left < right {
if s[left] != s[right] {
return false
}
left++
right--
}
return true
}
// 创建链表
// 尾插法
// time O(N) space O(1)
func createListFromTail(nums []int) *ListNode {
var head, tail, curr *ListNode
curr = &ListNode{}
head = curr
for _, value := range nums {
// 新建节点,并指向尾节点
node := &ListNode{Val: value}
node.Next = tail
curr.Next = node
curr = node
}
return head.Next
}
// 创建链表
// 头插法
// time O(N), space O(1)
func createListFromHead(nums []int) *ListNode {
var prev, curr *ListNode
for _, value := range nums {
node := &ListNode{}
node.Val = value
node.Next = prev
curr = node
prev = curr
}
return curr
}
func printLinkedList(head *ListNode) {
for head != nil {
if head.Next != nil {
fmt.Printf("%d->", head.Val)
} else {
fmt.Printf("%d", head.Val)
}
head = head.Next
}
fmt.Println()
}