First, the subject description:
Given a sorted list , delete all of the nodes contain repeated digits, leaving only the digital original list is not recurring.
Example 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
Example 2:
输入: 1->1->1->2->3
输出: 2->3
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Second, the problem-solving ideas:
1, and traverse the list to find whether the element is repeated.
2, if not repeat, create a new list, add a new element to the current list.
3, if duplicate, delete duplicate nodes.
Given a sorted list: that the current list and orderly, repeating certain elements adjacent.
Third, Code Description:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
//创建一个新链表
ListNode newHead=new ListNode(-1);
ListNode newTail=newHead;
ListNode cur=head;
while(cur!=null){
//针对某个引用进行 . 操作的时候, 必须保证该引用不能是 null
if(cur.next!=null&&cur.val==cur.next.val){
//当前元素是重复元素,查找重复元素区间。
while(cur.next!=null&&cur.val==cur.next.val){
cur=cur.next;
}
//while循环结束后,cur指向重复元素中的最后一个位置。
//cur向前再走一步,跳过了整个相同元素的区间。
cur=cur.next;
}
else{
//当前元素不是重复元素,插入到新链表中
newTail.next=new ListNode(cur.val);
newTail=newTail.next;
cur=cur.next;
}
}
return newHead.next;
}
}