Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
» Solve this problem
Given
1->1->2, return 1->2.Given
1->1->2->3->3, return 1->2->3.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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