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
.
The title means to delete the repeating element in the linked list
Idea: Traverse the list, with two pointers, one pointing to the previous one, one pointing to the next, when the two points are not equal, while the backward, when two points to the same value, you need to delete an element (the value pointed to by the latter pointer), and then backward traversal
The code is as follows:
<span style= "FONT-SIZE:18PX;" >/** * 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,*q,*pur; P=head; q=p->next; while (Q!=null) { if (p->val==q->val) { pur=q; q=q->next; p->next=q; Delete pur; } else { p=q; q=q->next; } } return head; }; </span>
Remove duplicates from Sorted List Leetcode