83. Remove Duplicates from Sorte

2017-11-14  本文已影响0人  Icytail

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

猜你喜欢

热点阅读