題解 | #刪除有序鏈表中重復(fù)的元素-II#
刪除有序鏈表中重復(fù)的元素-II
http://fangfengwang8.cn/practice/71cef9f8b5564579bf7ed93fbe0b2024
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代碼中的類名、方法名、參數(shù)名已經(jīng)指定,請(qǐng)勿修改,直接返回方法規(guī)定的值即可 * * * @param head ListNode類 * @return ListNode類 */ public ListNode deleteDuplicates (ListNode head) { // write code here if (head == null) { return null; } if (head.next == null) { return head; } ListNode nHead = new ListNode(-1); nHead.next = head; ListNode cur = nHead; while (cur.next != null && cur.next.next != null) { if (cur.next.val == cur.next.next.val) { int tmp = cur.next.val; while (cur.next != null && tmp == cur.next.val) { cur.next = cur.next.next; } } else { cur = cur.next; } } return nHead.next; //為什么設(shè)置頭節(jié)點(diǎn),因?yàn)榈谝粋€(gè)節(jié)點(diǎn)可能被刪除 } }