给定一个排序好的链表,删除所有重复元素使每个元素只出现一次。

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

解法1:

双指针法,定义一个指针 prev 指向新链表的末尾,另一个指针 curr 指向当前遍历的节点。

/**
 * 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 head;
    let root = new ListNode(null);
    let prev = root;
    let curr = head;
    while (curr) {
        if (!curr.next) {
            prev.next = curr;
        } else if (curr.val !== curr.next.val) {
            prev.next = curr;
            prev = prev.next;
        }
        curr = curr.next;
    }
    return root.next;
};

解法2:

直接遍历,将中间重复节点剪掉。

/**
 * 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 head;
    
    let curr = head;
    while (curr.next) {
        if (curr.val == curr.next.val) {
            curr.next = curr.next.next;
        } else {
            curr = curr.next;
        }
    }
    return head;
};