Created
June 18, 2013 03:20
-
-
Save luoxiaoxun/5802463 to your computer and use it in GitHub Desktop.
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 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
| C++: | |
| /** | |
| * 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) return NULL; | |
| ListNode *pPrePre=NULL; | |
| ListNode *pPre=NULL; | |
| ListNode *p=head; | |
| int key=INT_MAX; | |
| while(p){ | |
| if(p->val!=key){ | |
| key=p->val; | |
| pPrePre=pPre; | |
| pPre=p; | |
| p=p->next; | |
| }else{ | |
| if(pPre&&pPre->val==key){ | |
| ListNode *pNext=p->next; | |
| if(pPrePre) pPrePre->next=pNext; | |
| if(pPre==head) head=pNext; | |
| pPre=pPrePre; | |
| p=pNext; | |
| }else{ | |
| ListNode *pNext=p->next; | |
| if(pPre) pPre->next=pNext; | |
| if(p==head) head=pNext; | |
| p=pNext; | |
| } | |
| } | |
| } | |
| return head; | |
| } | |
| }; | |
| Java: | |
| /** | |
| * Definition for singly-linked list. | |
| * public class ListNode { | |
| * int val; | |
| * ListNode next; | |
| * ListNode(int x) { | |
| * val = x; | |
| * next = null; | |
| * } | |
| * } | |
| */ | |
| public class Solution { | |
| public ListNode deleteDuplicates(ListNode head) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| if(head==null) return null; | |
| ListNode pPrePre=null; | |
| ListNode pPre=null; | |
| ListNode p=head; | |
| int key=Integer.MAX_VALUE; | |
| while(p!=null){ | |
| if(p.val!=key){ | |
| key=p.val; | |
| pPrePre=pPre; | |
| pPre=p; | |
| p=p.next; | |
| }else{ | |
| if(pPre!=null&&pPre.val==key){ | |
| ListNode pNext=p.next; | |
| if(pPrePre!=null) pPrePre.next=pNext; | |
| if(pPre==head) head=pNext; | |
| pPre=pPrePre; | |
| p=pNext; | |
| }else{ | |
| ListNode pNext=p.next; | |
| if(pPre!=null) pPre.next=pNext; | |
| if(p==head) head=pNext; | |
| p=pNext; | |
| } | |
| } | |
| } | |
| return head; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment