美文网首页LeetCode
LeetCode刷题之Remove Duplicates fro

LeetCode刷题之Remove Duplicates fro

作者: JRTx | 来源:发表于2017-08-26 14:01 被阅读0次
    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;
    }
    

    相关文章

      网友评论

        本文标题:LeetCode刷题之Remove Duplicates fro

        本文链接:https://www.haomeiwen.com/subject/ubwmdxtx.html