Question:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Tips:將一個有序連結串列中的重複val的結點刪除。
思路:
設定一個指標,當指標下一個結點的val值與當前指標val相等就指標指向下一個結點的下一個。
cur.next=cur.next.next;
程式碼:
public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) return head; ListNode cur = head; while (cur != null) { if(cur.next!=null){ if (cur.val == cur.next.val) { cur.next=cur.next.next; }else{ cur=cur.next; } }else break; } return head; }
遞迴:
public ListNode deleteDuplicates2(ListNode head) { if (head == null || head.next == null) return head; head.next =deleteDuplicates2(head.next); return head.val==head.next.val?head.next:head; }