【题目概述】
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.
Given linked list – head = [4,5,1,9], which looks like following:
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
【思路分析】
- 题目中给的条件比较清晰,确定所给的节点不是尾结点,可以尝试将尾结点删除代码加入其中
【代码示例】
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
// if(node->next == NULL)
// {
// //无法直接找到上一个节点
// p = node;//保留尾结点之前的节点,可用于删除尾结点
// node = node->next;
// }
struct ListNode *rmnode = node->next;
//此处直接引用rmnode,比用node重新去找省时,少了一次寻址时间
node->val = rmnode->val;
node->next = rmnode->next;
free(rmnode);
}