83. 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 /** 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 if(head == NULL || head->next == NULL) 13 { 14 return head; 15 } 16 ListNode* h = head; 17 ListNode* l = head->next; 18 while(l != NULL) 19 { 20 if(h->val == l->val) 21 { 22 l = l->next; 23 if(l == NULL) 24 { 25 h->next = NULL; 26 } 27 } 28 else 29 { 30 h->next = l; 31 h = h->next; 32 l = l->next; 33 } 34 } 35 return head; 36 } 37 };