题目描述:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
算法实现:
和上一个问题极其类似82. Remove Duplicates from Sorted List II,将原来记录重复元素前一个元素的指针指向重复元素的第一个元素即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL)return head;
ListNode *p1, *p2;
p1 = head;
p2 = head;
while(p1 -> next != NULL){
p2 = p1;
while(p1 -> next != NULL && p1 -> next -> val == p1 -> val){
p1 = p1 -> next;
}
if(p1 -> next == NULL){
p2 -> next = NULL;
break;
}
p1 = p1 -> next;
p2 -> next = p1;
}
return head;
}
};