funcmiddleNode(head *ListNode) *ListNode { var low = head var fast int for head.Next != nil{ if fast % 2 == 0{ low = low.Next } head = head.Next fast++ } return low }
funchasCycle(head *ListNode)bool { var linkMap = make(map[*ListNode]struct{}) for head != nil && head.Next != nil{ if _, ok := linkMap[head]; ok{ returntrue } linkMap[head] = struct{}{} head = head.Next } returnfalse }
方法二:快慢指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funchasCycle(head *ListNode)bool { if head == nil { returnfalse } var low, fast = head, head.Next for fast != nil && fast.Next != nil{ if low == fast{ returntrue } low = low.Next fast = fast.Next.Next } returnfalse }
funcdetectCycle(head *ListNode) *ListNode { var linkMap = make(map[*ListNode]struct{}) for head != nil && head.Next != nil{ if _, ok := linkMap[head]; ok{ return head } linkMap[head] = struct{}{} head = head.Next } returnnil }
funcdetectCycle(head *ListNode) *ListNode { if head == nil { returnnil } var low, fast = head, head for fast != nil && fast.Next != nil{ low = low.Next fast = fast.Next.Next if low == fast{ var ptr = head for ptr != low{ ptr = ptr.Next low = low.Next } return ptr } } returnnil }
// findLinkCenterNode 找到链表的中心节点 funcfindLinkCenterNode(head *ListNode) *ListNode{ var low, temp = head, head var fast int for temp != nil{ if fast % 2 == 0{ low = low.Next } fast++ temp = temp.Next } return low }
// reverseLink 反转链表 funcreverseLink(head *ListNode) *ListNode{ var pre *ListNode var cur = head for cur != nil{ temp := cur.Next cur.Next = pre pre = cur cur = temp } return pre }
// mergeLink 合并链表 funcmergeLink(left, right *ListNode){ for left != nil && right != nil{ var ln, rn = left.Next, right.Next left.Next = right right.Next = ln left = ln right = rn } left.Next = nil }
funcremoveNthFromEnd(head *ListNode, n int) *ListNode { var list = make([]*ListNode, 0) var res = head for head != nil{ list = append(list, head) head = head.Next }
deleteNode := len(list) - n if deleteNode > 0 { pre := deleteNode - 1 if pre + 2 > len(list) - 1{ list[pre].Next = nil }else{ list[pre].Next = list[pre + 2] } return res } if deleteNode == 0 && len(list) > 1{ return list[1] }
returnnil }
改进算法实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcremoveNthFromEnd(head *ListNode, n int) *ListNode { var dummy = &ListNode{0, head} var low, fast = dummy, head for i := 0; i < n; i++{ fast = fast.Next }
for ; fast != nil; fast = fast.Next{ low = low.Next }
funcdeleteDuplicates(head *ListNode) *ListNode { var res = head var pre = &ListNode{101, head} for ; head != nil; head = head.Next{ if head.Val == pre.Val{ pre.Next = head.Next continue } pre = head } return res }