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
.
Subscribe to see which companies asked this question
//利用两个结点指针cur和temp,cur表示当前结点,temp表示下一个结点
//如果当前结点的值与下一个结点的值相等,则让当前结点的指针指向下一个结点的下一个结点即可
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
else
{
ListNode* cur = head;
ListNode* temp = head->next;
while (temp){
if (cur->val == temp->val)
{
cur->next = temp->next;
temp = cur->next; //注意此时前一个temp的位置已经找不到,应该利用cur移动到cur的下一个结点
}
else
{
cur = cur->next; //循环后移
temp = temp->next;
}
}
return head;
}
}
};