[LeetCode]Remove Duplicates from Sorted List II Java

簡單說一下自己的思路:

首先要確定一個頭,第一個不是重複數字的頭,第一個循環確定本身不是空置且有下一個節點,取頭節點值,和後面的對比,如果相同就繼續找不同的。頭結點和下一個節點相同則可以確定頭節點。

然後就是去除鏈表上的重複節點,cur指向的是肯定不是重複結點,首先指向頭,然後指向頭下兩個不同節點中的第一個,然後依次向下找。

感覺還是比較清晰的,就是代碼行數太多了。優點是用的常數空間

public class RemoveDuplicatesfromSortedListII{
	public static ListNode deleteDuplicates(ListNode head) {
		if (head == null || head.next == null) {
			return head;
		}
		while (head != null && head.next != null) {
			int first = head.val;
			if (head.next.val != head.val) {
				break;
			}
			while (head != null && head.val == first) {
				head = head.next;
			}
		}
		if (head == null) {
			return head;
		}
		ListNode cur = head;
		while (cur != null && cur.next != null) {
			if (cur.next != null && cur.next.next == null) {
				break;
			}
			if (cur.next.val == cur.next.next.val) {
				int temp  = cur.next.val;
				while (cur.next != null && cur.next.val == temp) {
					cur.next = cur.next.next;
				}
				continue;
			}
			cur = cur.next;
		}
		return head;
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章