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
.
The difference from the previous (http://www.cnblogs.com/grandyang/p/4066453.html) Is that all the repeated items should be deleted here, because there may be repeated items at the beginning of the chain table, the header pointer will change if it is deleted, in the end, the head pointer of the linked list needs to be returned. Therefore, you need to define a new node, link it to the original linked list, and then define a forward pointer and a current pointer. Whenever the forward Pointer Points to the new node, the current pointer starts to traverse from the next position, when the same element is encountered, continue until different items are encountered, and point the next of the precursor pointer to the different element below. If the first element of the current pointer traversal is different, the forward pointer is moved down by 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 || !head->next) return head; ListNode *start = new ListNode(0); start->next = head; ListNode *pre = start; while (pre->next) { ListNode *cur = pre->next; while (cur->next && cur->next->val == cur->val) cur = cur->next; if (cur != pre->next) pre->next = cur->next; else pre = pre->next; } return start->next; }};
Remove duplicates from sorted List II remove duplicate items in the ordered linked list