LeetCode

LeetCode刷题之Remove Duplicates fro

2017-08-26  本文已影响0人  JRTx
Problem

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.
My Solution

/**
 * 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 p, q;
        if (head == null || head.next == null) {
            return head;
        } else {
            p = head;
            q = head.next;
        }
        while (q != null) {
            if (p.val != q.val) {
                p = p.next;
                p.val = q.val;
            }
            q = q.next;
        }
        p.next = null;
        return head;
    }
}
Great Solution

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;
}
上一篇下一篇

猜你喜欢

热点阅读