Skip to content

Latest commit

 

History

History
56 lines (49 loc) · 1.31 KB

02-Remove-Duplicates-from-Sorted-List.md

File metadata and controls

56 lines (49 loc) · 1.31 KB

Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example, Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

解法

funcdeleteDuplicates(head*ListNode) *ListNode { p:=headforp!=nil&&p.Next!=nil { ifp.Val!=p.Next.Val { p=p.Next } else { p.Next=p.Next.Next } } returnhead }

Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example, Given 1->2->3->3->4->4->5, return 1->2->5.

Given 1->1->1->2->3, return 2->3.

pre 节点存上一个节点地址,初始值用了一个临时的节点 temp ,避免第一个节点就开始重复的情况。

funcdeleteDuplicates(head*ListNode) *ListNode { p, temp:=head, &ListNode{ Next: head } pre:=tempforp!=nil&&p.Next!=nil { ifp.Val!=p.Next.Val { pre=pp=p.Next } else { n:=p.Next.Nextforn!=nil&&n.Val==p.Val { n=n.Next } pre.Next=np=n } } returntemp.Next }
close