leetcode 82. Remove Duplicates from Sorted List II

时间:2023-03-08 22:16:58

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

题意:

给出一个链表,删除所有重复的结点。

步骤:

(1)定义一个新的头结点,用来指向head,并将head向前移动一位。

1  ->   1  ->  1  ->   2  ->  3

变为    head  ->  1  ->   1  ->  1  ->   2  ->  3

(2)遍历各结点,每次比较两个结点,head.next和head.next.next.

1. 如果head.next.val == head.next.next.val, 两个结点的值相等,用temp记录这个值,

从next开始依次遍历删除每个值为temp的结点,head.next = head.next.next.

2. 如果next和next.next的值不相等,继续向后遍历,head =head.next;

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null; ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy; while(head.next != null && head.next.next != null){
if(head.next.val == head.next.next.val){
int temp = head.next.val;
while(head.next != null && head.next.val == temp){
head.next = head.next.next;
}
}else{
head = head.next;
}
}
return dummy.next; }
}