LeetCode链接:力扣
题目:
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
示例一:
输入:head = [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() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
//删除头节点
while(head != null && head.val == val){
ListNode tmp = head;
head = head.next;
}
//删除非头节点
ListNode cur = head;
while(cur != null && cur.next != null){
if(cur.next.val == val){
ListNode tmp = cur.next;
cur.next = cur.next.next;
}else{
cur = cur.next; //继续移到下一节点
}
}
return head;
}
}
代码二:(建立虚拟头节点)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode cur = dummyHead;
while(cur.next != null){
if(cur.next.val == val){
ListNode tmp = cur.next;
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
head = dummyHead.next;
return head;
}
}