"083-remove duplicates from Sorted list (to remove duplicate nodes in a sorted single-linked list)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Main Topic
Given a single linked list, delete the duplicate elements and keep only one.
Thinking of solving problems
Use a pointer to the head of the list, and if the next is equal to the current node, delete until a different one is encountered, and the pointer points to the new node, repeating the operation until all the nodes have finished processing.
Code Implementation
Node class
publicclass ListNode { int val; ListNode next; ListNode(int x) { val = x; null; }}
Algorithm implementation class
Public classSolution { PublicListNodedeleteduplicates(ListNode head) {ListNode point; ListNode tail = head;//point to the end of the new node, start the chain with only one element, that is, the chain head if(Head! =NULL) {point = Head.next;//point to the head of the other chain while(Point! =NULL) {//The other chain is not yet at the end if(Tail.val! = point.val) {//If it is not the same as the tail node, link the different nodes to the next location of tailTail.next = point; tail = Tail.next;//re-pointing the end of the chain} point = Point.next; } Tail.next =NULL;//chain tail pointing to null}returnHead }}
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/47270975"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "083-remove Duplicates from Sorted list (to remove duplicate nodes in a sorted single-linked list)"