题意: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.
意思是:删除单向链表中的某一节点
但是!题目给的参数很有意思,只是给了需要删除的那个节点,而不是整个链表和需要被删除节点的索引
Java代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
if(node == null) return;
node.val = node.next.val;
node.next = node.next.next;
}
}
C代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
解题思路:既然只提供了一个要删的节点,那么先把当前节点的值用下一个节点的值覆盖了,然后我们删除下一个节点即可
因篇幅问题不能全部显示,请点此查看更多更全内容