码疯窝

LeetCode 每日一题 — Remove Linked List Elements

2015/04/26 23:26:21    分类: 日志连载    0人评论 次浏览

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

算法分析: 此题是相当基础的了, 只是需要多考虑一下如果根节点也要移处的情况.

PS: 终于可以用我的大爱javascript来做题目了, js越来越高能了. 曾经那个被人当作是网页脚本的语言已经跟C, C++, Java在同一起跑线了.

JavaScript:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var removeElements = function(head, val) {
    var parent = null, tmp = null;
    if (!head) return head;
    if (!head.next) return (head.val === val) ? null : head;
    while(head) {
        if (head.val !== val) break;
        head = head.next;
    }
    parent = head;
    while(parent) {
        if (!parent.next) break;
        tmp = parent.next;
        if (tmp.val === val)
            parent.next = tmp.next;
        else
            parent = parent.next;
    }
    return head;
};
继续查看有关 日志连载的文章

0个访客评论