LeetCode 之 刪除連結串列重複的元素(簡單 連結串列)
阿新 • • 發佈:2018-11-07
問題描述
給定一個排序連結串列,刪除所有重複的元素,使得每個元素只出現一次。
示例 1:
輸入: 1->1->2 輸出: 1->2
示例 2:
輸入: 1->1->2->3->3 輸出: 1->2->3
簡單的一批,直接程式碼
預設節點類
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode pre = head; ListNode next = head.next; while (next.next != null) { if (next.val == pre.val) { next = next.next; pre.next = next; }else { pre = next; next = next.next; } } if (next.val == pre.val){ pre.next = null; } return head; }
下邊是大神寫的
public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while (current != null && current.next != null) { if (current.next.val == current.val) { current.next = current.next.next; } else { current = current.next; } } return head; }