Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from the Original list.
For example,
Given1->2->3->3->4->4->5
, return1->2->5
.
Given1->1->1->2->3
, return2->3
.
Idea: This question in just start to do when thinking of a bit, how can not be solved correctly. Rewrite all of the code to remove it later. The idea is to record the current node P=head, then head down, and when the head value is not equal to the value of Head.next, it ends. Compare P==head, equal description not repeated, connected. The inequality indicates that there are repeated, skipping on it can be.
Detailed code such as the following:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {public ListNode deleteduplicates (ListNode head) { ListNode first = new ListNode (0); ListNode last = first; ListNode p = head; while (head = null) { while (head.next! = null) {//p does not move, head moves back until Head.next and p are unequal if (p.val = = head.next.val) { Head = head.next;//equal loop }else{ break;//Not Equal end } if (p = = head) {//Only one Last.next = p;/ /Join Last = Last.next; } p = head = head.next;//There are multiple then do not join last.next = null;//Remove association }return first.next;} }
Leetcode 82.Remove duplicates from Sorted List II (delete sort list repeat II) thinking and method of solving problems