203. Remove Linked List Elements

题目:

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.

 

Hide Tags
 Linked List 

链接:  http://leetcode.com/problems/remove-linked-list-elements/

题解:

在链表中移除目标值。 也是维护一个dummy node,当下一节点的值为target值时,设置下一节点 = 下一节点.下一节点,之后进行下一次判断,否则当前节点移动到下一节点。

Time Complexity - O(n), Space Complexity - O(1)。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode node = dummy;
        
        while(node.next != null){
            if(node.next.val == val)
                node.next = node.next.next;
            else
                node = node.next;
        }
        
        return dummy.next;
    }
}

 

Update:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        head = dummy;
        
        while(head.next != null) {
            if(head.next.val == val)
                head.next = head.next.next;
            else
                head = head.next;
        }
        
        return dummy.next;
    }
}

 

二刷:

设置一个fakehead,然后跟一刷一样

Java:

Time Complexity - O(n), Space Complexity - O(1)。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode node = dummy;
        while (node.next != null) {
            if (node.next.val == val) {
                node.next = node.next.next;
            } else {
                node = node.next;
            }
        }
        return dummy.next;
    }
}

 

三刷:

Java:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode node = dummy;
        while (node.next != null) {
            if (node.next.val == val) node.next = node.next.next;
            else node = node.next;
        }
        return dummy.next;
    }
}

 

 

 

Reference:

posted @ 2015-05-11 03:46  YRB  阅读(374)  评论(0编辑  收藏  举报