203. 移除链表元素

这篇博客讨论了如何在单链表中删除所有具有特定值的节点。提供了两种不同的解决方案,均通过创建新的链表来实现,将不符合条件的节点添加到新链表中。第一种方法在找到新节点时才初始化新链表,而第二种方法一开始就创建一个新节点作为新链表的头结点。两种方法最后都会返回新链表的头结点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 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) {
		if (head == null) return null;

		// 新链表的头结点
		ListNode newHead = null;
		// 新链表的尾结点
		ListNode newTail = null;

		while (head != null) {
			if (head.val != val) {
				// 将head拼接到newTail的后面
				if (newTail == null) {
					newHead = head;
					newTail = head;
				} else {
					newTail.next = head;
					newTail = head;
				}
			}
			head = head.next;
		}
		if (newTail == null) {
			return null;
		} else {
			// 尾结点的next要清空
			newTail.next = null;
		}
		return newHead;
    }
}



/**
 * 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) {
		if (head == null) return null;
		// 新链表的头结点
		ListNode newHead = new ListNode(0);
		// 新链表的尾结点
		ListNode newTail = newHead;
		while (head != null) {
			if (head.val != val) {
				newTail.next = head;
				newTail = head;
			}
			head = head.next;
		}
		newTail.next = null;
		return newHead.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值