There is a singly-linked list head and we want to delete a node node in it.
You are given the node to be deleted node. You will not be given access to the first node of head.
All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.
Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
The value of the given node should not exist in the linked list.
The number of nodes in the linked list should decrease by one.
All the values before node should be in the same order.
All the values after node should be in the same order.
Custom testing:
For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list.
We will build the linked list and pass the node to your function.
The output will be the entire list after calling your function.
看题目有点茫然,不知道让干嘛。
然后分析一下是这样的:
测试平台有一个单向链表(但是不会给你),它会调用deleteNode(node)函数(你负责实现这个函数),
调用完之后node这个节点会被删掉。
所以你知道的信息只有node这个节点,链表本身是什么你并不知道。
node不是tail节点。
思路:
我们负责实现的是deleteNode这个函数,传来的信息只有要删除的节点node.
同时还有node.next, node.val这些信息。
由于没有前一个节点,并不能删掉node本身,但可以删掉下一节点。
题目中也说了,删除node并不意味着要把node移出内存,只是要求它的值不在链表中出现,
链表保持原顺序即可,
而且node不是tail节点,这说明我们可以删除下一节点,然后把node的值变为下一节点的值即可。
public void deleteNode(ListNode node) {
ListNode nextNode = node.next;
int nextVal = nextNode.val;
node.next = nextNode.next;
nextNode.next = null;
node.val = nextVal;
}