题目
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
代码模板:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
}
}
分析
新建一个ListNode,循环head,如果当前是要删掉的数,就把下一个数赋给下一个指针,否则把当前数赋给下一个指针。
解答
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode current = new ListNode(0);
ListNode result = current;
while(head != null){
if(val == head.val){
current.next = head.next;
}else{
current.next = head;
current = current.next;
}
head = head.next;
}
return result.next;
}
}