美文网首页
83. Remove Duplicates from Sorte

83. Remove Duplicates from Sorte

作者: hyhchaos | 来源:发表于2016-12-06 11:02 被阅读13次

    Java

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

    Javascript

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var deleteDuplicates = function(head) {
            var tmp=head;
            while(tmp!==null)
            {
                if(tmp.next!==null&&tmp.val==tmp.next.val)
                {
                    tmp.next=tmp.next.next;
                    
                }
                else
                {
                    tmp=tmp.next;
                }
            }
            return head;
    };
    

    优解

    Java,用了递归的方法,想法很不错,比较难理解

    public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null)return head;
            head.next = deleteDuplicates(head.next);
            return head.val == head.next.val ? head.next : head;
    }
    

    相关文章

      网友评论

          本文标题:83. Remove Duplicates from Sorte

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