82. Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have 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
.
该题意思是删除链表中的重复数字,由于链表的head也可能被删除,因此需要加一个dummy node,可以使代码更加简洁
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) return head; //建一个dummy node,指向链表头部 ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; //当链表结点的next和next.next均不为空时循环,因为需要比较这两个结点的val是否相等 while (head.next != null && head.next.next != null) { if (head.next.val == head.next.next.val) { //记录下重复的值 int val = head.next.val; //遍历删除所有值重复的结点 while (head.next != null && head.next.val == val) { head.next = head.next.next; } } else { head = head.next; } } return dummy.next; } }