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 /** 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 ListNode *p; 15 p = head; 16 if(!p) return head; 17 18 while(p->next){ 19 if(p->next->val == p->val){ 20 ListNode *q; 21 q=p->next; 22 p->next = q->next; 23 delete q; 24 } 25 else{ 26 p = p->next; 27 28 } 29 } 30 31 return head; 32 } 33 };
思路:考察链表的基本操作,只要注意细节就没问题。