1. 程式人生 > >[LeetCode] 83. Remove Duplicates from Sorted List

[LeetCode] 83. Remove Duplicates from Sorted List

題目

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

題目大意

去除 有序連結串列 中的重複值

思路

方法一

對與當前 node,找下個 與node 不用的結點,將當前node指向下個 node。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode lp = head; while(lp!=null){ ListNode p = lp.next; while(p!=null && lp.val == p.val) p = p.next; lp.next = p; lp =
lp.next; } return head; } }

方法二

若下個node 與當前node不同,向下遍歷;否則 提出下個node。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head)
{ if(head == null) return head; ListNode p = head; while(p.next!=null){ if(p.next.val == p.val){ p.next = p.next.next; } else{ p = p.next; } } return head; } }