[leetcode]82. Remove Duplicates from Sorted List
3368 ワード
第1題:チェーンテーブルを遍歴し、重複ノードに遭遇したら次のノードに接続します.
第2題:構想は比較的に簡単で、1つの先頭ノードをheadの前ノードとして設定して、下を遍歴して、繰り返しに出会って先頭ノードを新しいvalノードに接続します.
最初のノードを常に削除するには、先頭ノードを設定します.
転載先:https://www.cnblogs.com/stAr-1/p/8441120.html
public ListNode deleteDuplicates(ListNode head) {
if (head==null||head.next==null) return head;
ListNode res = head;
while (head.next!=null){
if (head.val==head.next.val)
{
if (head.next.next!=null) head.next = head.next.next;
else head.next = null;
}
else head = head.next;
}
return res;
}
第2題:構想は比較的に簡単で、1つの先頭ノードをheadの前ノードとして設定して、下を遍歴して、繰り返しに出会って先頭ノードを新しいvalノードに接続します.
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null) return head;
ListNode res = new ListNode(0);
res.next = head;
ListNode list = res;
while (res.next!=null&&res.next.next!=null)
{
ListNode temp = res.next.next;
if (res.next.val==res.next.next.val)
{
while (temp.next!=null&&temp.next.val==temp.val)
{
temp = temp.next;
}
if (temp.next!=null) res.next = temp.next;
else res.next = null;
}
else res =res.next;
}
return list.next;
}
最初のノードを常に削除するには、先頭ノードを設定します.
転載先:https://www.cnblogs.com/stAr-1/p/8441120.html