题目:从一个有序链表里删除重复元素
分析:这个和数组去重很像。都只需记录下当前不重复的元素位置到下一个不重复的元素位置,然后建立联系即可。
答案:
/**
* 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) {
ListNode* pre = head;
if (head == NULL)
return head;
ListNode* nextp = head->next;
while(nextp){
if (nextp->val == pre->val){
nextp = nextp->next;
pre->next = NULL; // 临时先指向null
}
else{
pre->next = nextp;
pre = pre->next;
nextp = nextp->next;
}
}
return head;
}
};