[LeetCode 203] Remove Linked List Elements

来源:互联网 发布:知乎 单人沙发推荐 编辑:程序博客网 时间:2024/04/27 17:19

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


Solution:

1. go through linked list, compare value and remvoe

2.need to save head node

public ListNode removeElements(ListNode head, int val) {        ListNode newHead = new ListNode(0);        newHead.next = head;        ListNode p1 = newHead;        ListNode p2 = head;        while(p2!=null){            if(p2.val == val){                p1.next = p2.next;                p2 = p2.next;                continue;            }            p2 = p2.next;            p1 = p1.next;        }        return newHead.next;    }


0 0