脚本宝典收集整理的这篇文章主要介绍了[Leetcode] Delete Node/Remove Element in a Linked List 删除链表节点,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
赋值法
复杂度
时间 O(1) 空间 O(1)
思路
乍一看没法获取上一个链表节点,似乎无法将当前结点去除。实际上只要将下一个节点的值覆盖当前节点,然后删除下一个节点就好了。注意这样不适用于尾节点。
代码
public class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
Remove Linked List Elements
伪造表头
复杂度
时间 O(N) 空间 O(1)
思路
删除链表所有的特定元素的难点在于如何处理链表头,如果给加一个dummy表头,然后再从dummy表头开始遍历,最后返回dummy表头的next,就没有这么问题了。
代码
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode curr = dummy;
while(curr.next!=null){
if(curr.next.val == val){
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
return dummy.next;
}
}
以上是脚本宝典为你收集整理的[Leetcode] Delete Node/Remove Element in a Linked List 删除链表节点全部内容,希望文章能够帮你解决[Leetcode] Delete Node/Remove Element in a Linked List 删除链表节点所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。