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
.
首先我们把key设为非头节点的值,然后遍历链表,当节点值等于key时删除,不能于时更新key.
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *deleteDuplicates(ListNode *head) { 12 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 if (head == NULL) 15 return NULL; 16 17 ListNode *pPre = NULL; 18 ListNode *p = head; 19 int key = INT_MAX; 20 21 while(p) 22 { 23 if (key != p->val) 24 { 25 key = p->val; 26 pPre = p; 27 p = p->next; 28 } 29 else 30 { 31 ListNode *pNext = p->next; 32 if (pPre) 33 pPre->next = pNext; 34 delete p; 35 p = pNext; 36 } 37 } 38 39 return head; 40 } 41 };