LeetCode——删除链表中的节点

xiaoxiao2021-02-28  22

问题描述:删除链表中等于给定值 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; }
转载请注明原文地址: https://www.6miu.com/read-1600179.html

最新回复(0)