原题: https://leetcode-cn.com/problems/remove-linked-list-elements/
一、题目要求
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
二、解题
其中,ListNode结构见https://blog.csdn.net/qq_32523587/article/details/116356993。
package com.leetcode.test.linklist;
public class Solution4 {
public static void main(String[] args) {
ListNode a1 = new ListNode(1);
ListNode a2 = new ListNode(2);
ListNode a3 = new ListNode(6);
ListNode a4 = new ListNode(3);
ListNode a5 = new ListNode(4);
ListNode a6= new ListNode(5);
ListNode a7 = new ListNode(6);
a1.next = a2;
a2.next = a3;
a3.next = a4;
a4.next = a5;
a5.next = a6;
a6.next = a7;
ListNode b = removeElements(a1, 6);
while (b != null) {
System.out.print(b.val + " ");
b = b.next;
}
}
//遍历链表,值只要不等于val,则存入另一个链表中
public static ListNode removeElements(ListNode head, int val) {
if (head == null){
return null;
}
ListNode listNode = new ListNode();
ListNode cur = listNode;
while (head != null){
if (head.val != val){
ListNode l = new ListNode(head.val);
cur.next = l;
cur = l;
}
head = head.next;
}
return listNode.next;
}
}
三、运行结果
四、提交结果