LC 160. Intersection of Two Linked Lists 相交链表
https://leetcode.com/problems/intersection-of-two-linked-lists/description/
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func getIntersectionNode(headA, headB *ListNode) *ListNode { lA := getLength(headA) lB := getLength(headB) if lB < lA { headA, headB = headB, headA lA, lB = lB, lA } for i := 0; i < lB-lA; i++ { headB = headB.Next } for headA != headB { headA = headA.Next headB = headB.Next } return headA } func getLength(head *ListNode) int { l := 0 for head != nil { l++ head = head.Next } return l }
交替行走法
待复习
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func getIntersectionNode(headA, headB *ListNode) *ListNode { p1 := headA p2 := headB for p1 != p2 { if p1 == nil { p1 = headB } else { p1 = p1.Next } if p2 == nil { p2 = headA } else { p2 = p2.Next } } return p1 }
LC 82. Remove Duplicates from Sorted List II 删除排序链表中的重复元素 II
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/