问题描述:删除链表中等于给定值 val 的所有节点。
思路:使用三个引用保存当前节点,前一个节点,后一个节点。要考虑到删除的节点是头节点、尾节点、中间节点,删除后链表为空这些情况。
代码如下:
public ListNode RemoveElements(ListNode head, int val) {
while(head!=null && head.val==val)
head=head.next;
if(head==null)
return null;
ListNode preNode=head;
ListNode currentNode=head.next;
while(currentNode!=null)
{
if(currentNode.val==val)
{
preNode.next=currentNode.next;
currentNode=currentNode.next;
}
else
{
preNode=currentNode;
currentNode=currentNode.next;
}
}
return head;
}
本文介绍了一种从链表中删除所有等于给定值val的节点的方法。通过使用三个引用变量来跟踪当前节点、前一节点和后一节点,可以有效处理头节点、尾节点及中间节点的删除,并确保链表的一致性。
330

被折叠的 条评论
为什么被折叠?



