LeetCode 83. Remove Duplicates from Sorted List

題目

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.

翻譯

改一個排序過的連結陣列,刪除重複的節點。

範例:
[1,1,2] -> return [1,2]
[1,1,2,3,3] -> return [1,2,3]

思路

因為是排序過的,所以只要判斷後面的節點與當前的是否相同,如果後面的節點跟目前的相同,就跳過他。

解題

/**
 * 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 === null || head.next ===null) return head;
    var cur = head;

    while(cur.next !== null){
        // 如果目前Node的值與下一個相同,跳過下一個
        if(cur.val == cur.next.val){
            cur.next = cur.next.next;
        } else {
            cur = cur.next;
        }
    }
    return head;
};

results matching ""

    No results matching ""