Delete the node in the linked list
Title description: Please write a function to delete a given (non-end) node in a linked list. The only parameter passed into the function is , the node to be deleted.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/delete-node-in-a-linked-list/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Brain teasers
I didn't respond at the first time, why didn't I give the head node? ? ? After thinking for a while, I would like to understand why the parameter is not the end of the node. The solution is to change the value of the node to be deleted and next to the value of the next node of the node to be deleted and next.
public class LeetCode_237 {
public static void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
public static void main(String[] args) {
ListNode head = new ListNode(4);
head.next = new ListNode(5);
ListNode node_1 = new ListNode(1);
head.next.next = node_1;
head.next.next.next = new ListNode(9);
System.out.println("before deleteNode");
ListNode cur = head;
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.next;
}
System.out.println();
deleteNode(node_1);
System.out.println("after deleteNode");
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
}
[Daily Message] There is only one kind of heroism in the world, which is to still love life after recognizing the truth of life.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。