LeetCode 83 Remove Duplicates from Sorted List (Remove duplicate elements from Sorted List )(*)
Translation
Given a sorted Linked List, delete all repeated elements so that each element appears only once. For example, if 1-> 1-> 2 is specified, 1-> 2 is returned. Given 1-> 1-> 2-> 3-> 3, 1-> 2-> 3 is returned.
Original
Given a sorted linked list, delete all duplicates such that each element appear only once.For example,Given 1->1->2, return 1->2.Given 1->1->2->3->3, return 1->2->3.
Analysis
First, we should judge whether it is empty:
if (head == NULL) return NULL;if (head->next == NULL) return head;
However, the two lines of code can be abbreviated as follows:
if (head == NULL || head->next == NULL) return head;
The following is a loop statement:
while (head->next) { if (head->val == head->next->val) { head->next = head->next->next; } else { head = head->next; } }
The meaning is very simple. First, determine whether the value of the current node is equal to the value of the next node. If the value is equal, assign the next node to the next node.
Rewrite 1--1--2--3--3 to 1--2--3--3.
In this case Head Still 1 But why not move it 2 That is to say why the code is not like this:
while (head->next) { if (head->val == head->next->val) { head->next = head->next->next; head = head->next; } else { head = head->next; } }
The reason is simple, for example:
1--1--1--2--3--3 after the first transformation: 1--1--2--3--3 if you rashly move the head to the next node, the next comparison is comparison 1 and 2, which is obviously unreasonable.
Here, the removal operation is complete, but you can directly Returnhead Obviously, no, because Head It has been moved to the last node.
Therefore While A new Head As a record, return it.
ListNode* newHead = head;while(){}return newHead;
Code
/*** 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 || head->next == NULL) return head; ListNode* newNode = head; while (head->next) { if (head->val == head->next->val) head->next = head->next->next; else head = head->next; } return newNode; }};