Given a sorted linked list, delete all nodes that has 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
.
Two methods
Method One: Traverse the list two times, remove the duplicate node for the first time, and save the node value of each deletion into the container (the saved value is no longer saved), the second traversal, take out the value in the container, and delete the node of the same value in the list;
Method Two: One traversal, the pointer is more error prone;
In fact, the time complexity of the two methods is the same, but the method one uses the auxiliary space, method two does not.
Method One:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */listnode* deleteduplicates (listnode* head) {if (head==null) return null;if (head->next==null) return Head;vector <int> DeleteValue; listnode* P=head;int key=p->val;p=p->next; listnode* q=head;bool Flag=false;while (p) {if (P->val==key) {listnode* tobedeleted=p;q->next=tobedeleted-> Next;p=q->next;delete tobedeleted;tobedeleted=null;if (!flag) {deletevalue.push_back (key); flag=true;}} Else{key=p->val;flag=false;p=p->next;q=q->next;}} P=head;q=head;vector<int>::iterator Iter=deletevalue.begin (); while (P && iter!=deletevalue.end ()) {if (P->val==*iter) {if (p==head) {listnode* tobedeleted=p;p=tobedeleted->next;q=tobedeleted->next;head=q;delete toBeDeleted; Tobedeleted=null;} else{listnode* tobedeleted=p;q->next=tobedeleted->next;p=q->next;delete ToBeDeleted;toBeDeleted=NULL;} iter++;} Else{if (p!=q) q=q->next;p=p->next;}} return head;}
Method Two:
/** * 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; if (Head->next==null) return head; listnode* P=head; listnode* Q=head; listnode* k=p->next; BOOL Flag=false; while (k) {if (p->val==k->val) {if (p==q) {p=q=k; Head=k; k=k->next; } else {listnode* tobedeleted=k; p->next=tobedeleted->next; k=p->next; Delete tobedeleted; Tobedeleted=null; } flag=true; } else {if (flag) {if (p==q) {p=q=k; Head=k; k=k->next; Flag=false; } else {listnode* tobedeleted=p; q->next=tobedeleted->next; P=k; k=k->next; Delete tobedeleted; Tobedeleted=null; Flag=false; }} else {if (p!=q) q=q->next; P=p-&gT;next; k=k->next; }}} if (flag) {if (p==q) {delete p; P=null; return NULL; } listnode* tobedeleted=p; q->next=tobedeleted->next; Delete tobedeleted; Tobedeleted=null; } return head; }};
Leetcode (+): Remove duplicates from Sorted List II