Tuesday, July 2, 2013

remove duplicates from sorted lists@leetcode

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.
» Solve this problem
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head==NULL||head->next==NULL) return head;
ListNode *cur=head, *p=cur->next;
while(p->next!=NULL)
{
if(cur->val!=p->val)
{
cur->next=p;
cur=p;
p=p->next;
}
else
p=p->next;
}
if(p->val!=cur->val)
{
cur->next=p;
cur=p;
cur->next=NULL;
}
else
cur->next=NULL;
return head;
}
};

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...