Leetcode:237. 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 -> 4and you are given the third node with value3, the linked list should become1 -> 2 -> 4after calling your function.
0X02 题意
题目的要求就是删除链表中的一个元素,给的数据结构是一个单链表。
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }注意判断一下需要删除的节点是否为空、该节点是否是最后一个节点即可。
0X03 题解
1.解法一(Dante:Java)
比较直观的一个解法,判断一下需要删除的节点是否为空、该节点是否是最后一个节点即可。
-
时间复杂度O(N)
-
空间复杂度O(1)
public class Solution { public void deleteNode(ListNode node) { if(node == null) return; if(node.next == null){ node = null; return; } node.val = node.next.val; node.next = node.next.next; }