美文网首页
83. Remove Duplicates from Sorte

83. Remove Duplicates from Sorte

作者: Icytail | 来源:发表于2017-11-14 16:50 被阅读0次

    Description:

    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 code:

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var deleteDuplicates = function(head) {
        if(!head) {
            return null;
        }
        let singleArr = [], singleListNode = head; // 数组用于判断元素是否出现过
        let curListNode = head;
        while(head != null) {
            if(singleArr.indexOf(head.val) == -1) {
                singleArr.push(head.val);
                head = head.next;
            } else {         
                while(curListNode.next != null) { // 找出重复元素的第一个节点,删除它的下一个节点
                    if(curListNode.val == head.val) {
                        break;
                    } else {
                        curListNode = curListNode.next;    
                    }
                }
                curListNode.next = head.next;
                head = head.next;
            }
        }
        return singleListNode;
    };
    

    相关文章

      网友评论

          本文标题:83. Remove Duplicates from Sorte

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