Given a sorted linked list, delete all duplicates such this each element appear only once.
Example 1:
Input:1->1->2output:1->2
Example 2:
Input:1->1->2->3->3output:1->2->3
A simple list problem can be written in both recursive and iterative forms. Specific ideas:
The first step is to find the node with the first node value and the node value that the current header refers to.
In the second step, the next point of the current table head node points to the found node;
In the third part, recursion calls the first two steps, or the first two steps of the iteration call.
See below for detailed code comments.
Recursive solution (Java)
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/classSolution { PublicListNode deleteduplicates (ListNode head) {if(Head = =NULL|| Head.next = =NULL)returnHead;//special case processing, i.e. empty list and single node linked list return directly to ListNode cur=Head.next;//Set pointer to the first node after the table header while(cur! =NULL&& Cur.val = = head.val) cur =cur.next;///First, look for the node with the first node value and the node value different from the current table head node Head.next=deleteduplicates (cur);//when found, take the second step, that is, the current header node next point to the node you just found. Here is a recursive call, the above found on the non-repeating node is cur, then this recursive return is exactly the cur, and at the same time to perform the cur as a nod to workreturnHead ;//Return to First node}}
Iterative solution (Java)
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/classSolution { PublicListNode deleteduplicates (ListNode head) {if(Head = =NULL|| Head.next = =NULL)returnHead;//special case processing, same iterative solution ListNode pre=Head, cur=Head.next;//define two pointers pointing to the current head node and its next node, respectively while(cur! =NULL) { if(Cur.val = =pre.val) cur=Cur.next;//First step to find the first non-repeating nodeElse{Pre.next=cur;//Find a second step, that is, the current node pre's next point to the found node cur pre=cur;//After repeating the previous procedure cur=Pre.next; }} Pre.next=cur;//iterate to the end because Cur is null when it jumps out of the loop, does not perform the final deduplication, so add a sentence to make the end of the list no duplicate nodesreturnHead; }}
(Java) Leetcode 83. Remove duplicates from Sorted list--Remove duplicate elements from the sorted list