leetcode解题报告(6):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.
分析
只需要从头结点开始遍历,判断当前结点元素是否和下一个元素相等,如果相等,则跳过下一结点,否则直接让当前结点等于下一结点。
代码如下:
/**
* 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* tmp = head;
while(tmp){
while(tmp -> next && tmp -> val == tmp -> next -> val)
tmp -> next = tmp -> next -> next;
tmp = tmp -> next;
}
return head;
}
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL) return NULL;
ListNode* pre = head,*cur = head -> next;
while(cur){
if(pre -> val == cur -> val){
pre -> next = cur -> next;
cur = cur -> next;
}else{
pre -> val = cur -> val;
pre = pre -> next;
cur = cur -> next;
}
}
};