问题:
Given a sorted linked list, delete all duplicates such that each element appear onlyonce.
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)
{
if (head == NULL)
{
return NULL;
}
ListNode *current = head;
ListNode *next = current->next;
ListNode *temp = NULL;
while (next != NULL)
{
if (current->val != next->val)
{
current = next;
next = next->next;
}
else
{
temp = next;
next = next->next;
current->next = next;
temp = NULL;
}
}
return head;
}
};