funcremoveElements(head *ListNode, val int) *ListNode { dmHead := &ListNode{} dmHead.Next = head cur, pre := head, dmHead for cur != nil { if cur.Val == val { pre.Next = cur.Next } else { pre = pre.Next } cur = cur.Next } return dmHead.Next }
funcswapPairs(head *ListNode) *ListNode { dmHead := &ListNode{Next: head} pre, cur := dmHead, head for cur != nil && cur.Next != nil { next := cur.Next.Next pre.Next = cur.Next cur.Next.Next = cur cur.Next = next pre = cur cur = next } return dmHead.Next }
funcremoveNthFromEnd(head *ListNode, n int) *ListNode { var count int dmHead := &ListNode{Next: head} pre, cur := dmHead, head for cur != nil { if count != n { count++ } else { pre = pre.Next } cur = cur.Next } pre.Next = pre.Next.Next return dmHead.Next }
funcdetectCycle(head *ListNode) *ListNode { slow, fast := head, head for fast != nil && fast.Next != nil { slow = slow.Next fast = fast.Next.Next if slow == fast { for slow != head { slow = slow.Next head = head.Next } return head } } returnnil }