标签:style blog http color os io for ar
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.
删除排序链表中重复的节点,删除操作完成后,原链表中的重复节点只保留一个。
思路,遍历链表,如果当前节点和下一个节点重复,则删除下一个节点,不同则前进一个节点继续处理,直到链表结尾。
这道题比Remove Duplicateds from Sorted list II要简单一些,在删除完重复的下一个节点后,不需要再删除当前节点。
AC code:
/**
* 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 *p=head;
while(p!=NULL)
{
if(p->next==NULL||p->val!=p->next->val)
{
p=p->next;
continue;
}
ListNode *q=p->next;
p->next=q->next;
delete q;
}
return head;
}
};
leetcode 刷题之路 76 Remove Duplicates from Sorted List,布布扣,bubuko.com
leetcode 刷题之路 76 Remove Duplicates from Sorted List
标签:style blog http color os io for ar
原文地址:http://blog.csdn.net/u013140542/article/details/38493127