"082-remove duplicates from Sorted List II (remove duplicate elements in sort List II)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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 .
Main Topic
Given a well-ordered single-linked list, delete all duplicate elements. Leave only one element of value.
Thinking of solving problems
Attach a secondary node to the linked list Root,root to the original head, referring to the head and the auxiliary pointer, the heavy elements are deleted.
Code Implementation
Algorithm implementation class
Public class solution {PublicListNodeDeleteduplicates (ListNodeHead) {ListNoderoot = newListNode(0);//Head node root.Next= head;ListNodep = head;ListNodeQ = root;//Record the last element with no duplicates and start pointing to the head node int delta =0;//Number of elements to repeat while(P! = null && p.Next! = null) {if(P.val = = P.)Next. val) {//If the adjacent two numbers are the same delta++; p = P.Next;//Move to next node}Else{//If two adjacent nodes are not the sameif(Delta = =0) {//A node with a value of p.val does not repeat Q.Next= P;//Link to an element with no complex q = p;//Point to the last non-repeating element p = p.Next;//Move to next node}Else{//A node with a value of p.val has a repetition of p = p.Next;//Move to the next element, Q.Next= P.Next;//Remove the duplicate element delta =0;//The number of element repeats is set to0} } }if(Delta! =0) {//If the last element is complex, remove Q.Next= NULL; }Else{//If you do not repeat, link to footer Q.Next= P; }returnRoot.Next; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47270973"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "082-remove duplicates from Sorted List II (remove duplicate elements in sort List II)"