题目:
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)
{
if(head == NULL)
return NULL;
ListNode *q=head,*p = head->next;
while(p)
{
while( p && p->val == q->val )//循环结束条件为遇到不等的,或者p为尾结点
{
//q->next = p;
ListNode *tmp=p;
p = p->next ;
delete tmp;
}
if(p)//遇到的是不等的
{
q->next = p;
q=q->next;
p=p->next;
}
else//一直相等,直到p为尾结点,例如(1,1,1)
q->next = NULL;//则令q为尾结点
}
return head;
}
};
代码2:
/**
* 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 == nullptr)
return nullptr;
for (ListNode *prev = head, *cur = head->next; cur; cur = cur->next)
{
if (prev->val == cur->val)
{
prev->next = cur->next; //遇到的是相等的,prev则指向相等的结点的后一个,直到遇到不相等的为止
delete cur;
}
else
{
prev = cur;
}
}
return head;
}
};