203.移除链表元素
力扣题目链接(opens new window)
题意:删除链表中等于给定值 val 的所有节点。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
package com.leetcode.linkedlist;
/**
* 203.移除链表元素
* 力扣题目链接(opens new window)
*
* 题意:删除链表中等于给定值 val 的所有节点。
*
* 示例 1:
* 输入:head = [1,2,6,3,4,5,6], val = 6
* 输出:[1,2,3,4,5]
*
* 示例 2:
* 输入:head = [], val = 1
* 输出:[]
*
* 示例 3:
* 输入:head = [7,7,7,7], val = 7
* 输出:[]
*
*/
public class RemoveLinkValue {
public static void main(String[] args) {
}
public static class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){this.val = val;}
ListNode(int val, ListNode next){this.val = val; this.next = next;}
}
public static ListNode Solution(ListNode head, int val){
//增加一个头结点,
ListNode dummy = new ListNode(-1,head);
ListNode pre = dummy;
ListNode curr = head;
while (curr != null){
if(curr.val == val) pre.next = curr.next;
else pre = curr;
curr = curr.next;
}
return dummy.next;
}
public static ListNode Solution2(ListNode head, int val){
while (head != null && head.val == val){
head = head.next;
}
if(head == null) return null;
ListNode pre = head;
ListNode curr = head.next;
while (curr != null){
if(curr.val == val){
pre.next = curr.next;
}
else pre = curr;
curr = curr.next;
}
return head;
}
}