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

 

此题考查的是如何删除链表中某些节点,属于基本的链表题,直接上代码:

/**

 * 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(0);

        dummy.next = head;

        ListNode pre = dummy;

        ListNode cur = head;

        while(cur!=null){

            if(cur.val==val){

                pre.next = cur.next;

                cur = cur.next;

            }else{

                cur = cur.next;

                pre = pre.next;

            }

        }

        return dummy.next;

    }

}

posted @ 2017-01-28 09:58  CodesKiller  阅读(116)  评论(0编辑  收藏  举报