[LeetCode-JAVA] 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

思路:设置前置指针,并随之移动。

代码:

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode req = new ListNode(0);
        req.next = head;
        ListNode pre = req;
        
        while(head != null){
            if(head.val == val){
                pre.next = head.next;
            }else
                pre = pre.next;
            head = head.next;
        }
        
        return req.next;
    }
}

 

posted @ 2015-06-01 11:29  可爱的波儿胖  阅读(176)  评论(0编辑  收藏  举报

友情链接 : CodeForge源码分享