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
.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode deleteduplicates (ListNode head) {//Two methods of solution://a declaration of three nodes, one representing the requirements before index, first is the traversal of the node, the pre is the pre-set, easy to delete the node to retain the predecessor//one is that only one node is needed, and the node is compared with the subsequent values, if equal, directly deleted, if unequal points to the next node if(head==NULL|| head.next==NULL)returnHead; /*ListNode Pre=head; ListNode First=head.next; ListNode Index=head; while (First!=null) {if (index.val==first.val) {pre.next=first.next; First=first.next; }else{Pre=first; First=first.next; Index=index.next; }} return head;*/ListNode Pre=Head; while(pre.next!=NULL){ if(pre.next.val==pre.val) {Pre.next=Pre.next.next; }Else{Pre=Pre.next; } } returnHead; }}
[Leedcode 83] Remove Duplicates from Sorted List