LeetCode OJ - Remove Duplicates from Sorted List
If you want to use (copy, paste or quote) my original article, please contact me through email. (autek.roy@gmail.com) If there is any mistake or comment, please let me know. :D
如要使用(複製貼上或轉載)作者原創文章, 請來信跟我聯絡。(autek.roy@gmail.com) 如果有發現任何的錯誤與建議請留言或跟我連絡。 : )
This file contains 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) { | |
ListNode *tmpNode = head; | |
while(tmpNode){ | |
if(tmpNode->next != NULL && tmpNode -> val == tmpNode -> next -> val){ | |
ListNode *nextNode = tmpNode -> next -> next; | |
delete tmpNode -> next;//free memory | |
tmpNode -> next = nextNode; | |
} | |
else | |
tmpNode = tmpNode -> next; | |
} | |
return head; | |
} | |
}; |
This file contains 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) { | |
if(head == NULL) | |
return head; | |
int preVal = head -> val; | |
ListNode *preNode = head, *tmpNode = head -> next; | |
while(tmpNode != NULL){ | |
int nextVal = tmpNode -> val; | |
if(preVal == nextVal) | |
preNode -> next = tmpNode -> next; | |
else | |
preNode = tmpNode; | |
tmpNode = tmpNode -> next; | |
preVal = preNode -> val; | |
} | |
return head; | |
} | |
}; |
If you want to use (copy, paste or quote) my original article, please contact me through email. (autek.roy@gmail.com) If there is any mistake or comment, please let me know. :D
如要使用(複製貼上或轉載)作者原創文章, 請來信跟我聯絡。(autek.roy@gmail.com) 如果有發現任何的錯誤與建議請留言或跟我連絡。 : )
沒有留言:
張貼留言
請留下您的任何想法或建議!
Please leave any thought or comment!