Remove Duplicates from Sorted List

来源:互联网 发布:网络拓扑 软件 编辑:程序博客网 时间:2024/06/05 11:04

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.

Tags

LinkedList

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Easy Solution

/** * 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 node = head;    var last = node.val;    while (node.next !== null) {        if (node.next.val === last) {            node.next = node.next.next;        } else {            last = node.next.val;            node = node.next;        }    }    if (node.val === last) {        node = null;    }    return head;};


0 0
原创粉丝点击