Remove Duplicates from Sorted List II, duplicatessorted
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlyDistinctNumbers from the original list.
For example,
Given1->2->3->3->4->4->5
, Return1->2->5
.
Given1->1->1->2->3
, Return2->3
.
Consider the following situations:
1-> 1-> 1-> 3-> 3-> 3,
1-> 1-> 1
1-> 2-> 2-> 3,
1-> 2-> 2
Set three pointers. The front pointer pre and the front pointer prepre point to the header node. Currently, the pcur Pointer Points to the next pointer at the header node.
Set a FLAG to determine whether pcur and pre are equal.
1/** 2 * Definition for singly-linked list. 3 * struct ListNode {4 * int val; 5 * struct ListNode * next; 6 *}; 7 */8 struct ListNode * deleteDuplicates (struct ListNode * head) {9 struct ListNode * prepre; 10 struct ListNode * pre; 11 struct ListNode * pcur; 12 int flag = 0; // The flag bit is initialized to 013 if (head = NULL) 14 return NULL; 15 prepre = head; 16 pre = head; 17 pcur = head-> next; 18 while (pcur! = NULL) {19 if (pcur-> val! = Pre-> val & flag = 0) {// if the front pointer is not the same as the current pointer and there are no identical elements between them, all three pointers point to the next 20 prepre = pre; 21 pre = pcur; 22 pcur = pcur-> next; 23} 24 else if (pcur-> val = pre-> val) {// if the front pointer is equal to the current pointer 25 if (pcur-> next = NULL) {// if the current pointer is the last element 26 if (prepre = head & prepre-> val = pcur-> val) // determine whether the front pointer is a header node, and is equal to the current element, such as 1-> 1-> 1 27 return NULL; 28 else {29 prepre-> next = NULL; 30 break; 31} 32} 33 flag = 1; 34 pcur = pcur-> next; 35} 36 Else if (pcur-> val! = Pre-> val & flag = 1) {// if the front pointer is not the same as the current pointer, 37 if (prepre = head & prepre-> val = pre-> val) {// determine whether the front pointer is a header node and is equal to the front pointer 2-> 2-> 2-> 338 head = pcur; 39 prepre = head; 40 pre = pcur; 41 pcur = pcur-> next; 42 flag = 0; 43} 44 else {45 prepre-> next = pcur; 46 pre = pcur; 47 pcur = pcur-> next; 48 flag = 0; 49} 50} 51} 52 return head; 53}