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
从链表中删除节点为给定值得所有节点。对于在链表中删除节点的问题,如果头结点可能被删除的情况下,我们往往创建一个helper节点,让它指向头结点。这样从helper节点的next开始处理,最后返回help.next就可以了。代码如下:
/**
* 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 helper = new ListNode(0);
helper.next = head;
head = helper;
while(head.next != null) {
if(head.next.val == val) {
head.next = head.next.next;
} else {
head = head.next;
}
}
return helper.next;
}
}