Problem:
Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2 , return 1->2 .
Given 1->1->2->3->3 , return 1->2->3 .
Hide TagsLinked ListTest instructions: Removes duplicate elements from an already ordered single-linked list, leaving only one
Thinking:
(1) This problem is a simplified version of the previous question, the previous question is to duplicate the elements of a non-stay delete: http://blog.csdn.net/hustyangju/article/details/45028247
(2) Double pointer traversal, time complexity O (N), single commit AC
Code
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode *deleteduplicates (ListNode *head) { if (Head==null | | head->next==null) return Head; ListNode *p=head;//left pointer listnode *q=p;//Right pointer while (p!=null) { q=p->next;//Right pointer initialize if (q== NULL) return head; if (p->val!=q->val)//unequal, while advancing { p=p->next; q=q->next; } else/equal, right pointer forward {while (q!=null && q->val==p->val) { q=q->next; } p->next=q; Delete duplicate element p=q; Update left Pointer } } return head;} ;
Leetcode | | 83. Remove Duplicates from Sorted List