LeetCode OJ: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
.
简单的链表去重而已啊,遍历一边就实现了:
1 class Solution { 2 public: 3 ListNode* deleteDuplicates(ListNode* head) { 4 ListNode * p = head; 5 if(p == NULL || p->next == NULL) 6 return p; 7 ListNode * prev = p; 8 p = p->next; 9 while(p!=NULL){ 10 if(p->val == prev->val){ 11 prev->next = p->next; 12 }else{ 13 prev = p; 14 } 15 p = p->next; 16 } 17 return head; 18 } 19 };
下面这个实际上比上面那个要快一点,上面那个是遇到一个删掉一个,这个是遇到一连串相同的就一起删掉,java写的,runtime比上面又不小的提高,代码如下:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode deleteDuplicates(ListNode head) { 11 if(head == null) return null; 12 ListNode helper = new ListNode(-1); 13 helper.next = head; 14 ListNode p = head; 15 while(p.next!=null){ 16 if(p.val == p.next.val){ 17 ListNode tmp = p.next; 18 while(tmp.next != null){ 19 if(tmp.next.val == tmp.val){ 20 tmp = tmp.next; 21 }else 22 break;//找到最后一个和前面相同的节点 23 } 24 p.next = tmp.next; 25 tmp.next = null; 26 }else{ 27 p = p.next; 28 } 29 } 30 return helper.next; 31 } 32 }