Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given1->1->2
, return1->2
.
Given1->1->2->3->3
, return1->2->3
.
Main topic:
Remove the same elements within an ordered list, that is, the same element is reserved only one.
The code is as follows:
/** * 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 NULL; ListNode* p = head->next; listnode* pre = head; int cur = head->val; while (p != null) { if (Cur == p->val) { pre->next = p->next; } else { cur = p->val; pre = p; } p = p-> Next; } return head; }};
Other Concise practices:
1. Double while
Reference from: https://discuss.leetcode.com/topic/2168/concise-solution-and-memory-freeing
Class Solution {Public:listnode *deleteduplicates (ListNode *head) {listnode* cur = head; while (cur) {while (cur->next && cur->val = = cur->next->val) Cur->next = cur->next->next; Cur = cur->next; } return head; }};
2. Double pointer
Reference from: https://discuss.leetcode.com/topic/2168/concise-solution-and-memory-freeing
ListNode *deleteduplicates (ListNode *head) {listnode*cur=head,*tail=head; while (cur) {if (cur->val!=tail->val) {tail->next=cur; Tail=cur; } cur=cur->next; tail->next=null; } return head;
2016-08-12 12:37:15
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1837260
Leetcode 83. Remove duplicates from Sorted list linked list