题目描述:
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 return head; 14 ListNode* pre=head; 15 ListNode* cur=head->next; 16 while(cur!=NULL){ 17 if(pre->val==cur->val){ 18 cur=cur->next; 19 pre->next=cur; 20 } 21 else{ 22 pre->next=cur; 23 cur=cur->next; 24 pre=pre->next; 25 } 26 } 27 return head; 28 } 29 };