首页 > 代码库 > Remove Duplicates from Sorted List

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         if( !head ) { return head; } 5         ListNode *node = head; 6         while( node->next ) { 7             if( node->val == node->next->val ) { 8                 node->next = node->next->next; 9             } else {10                 node = node->next;11             }12         }13         return head;14     }15 };

 

Remove Duplicates from Sorted List