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 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
237.删除链表中的结点
写一个函数来删除一个单链表中的结点(非尾结点),而且只给出那个结点的地址。
假设一个链表如1->2->3->4,然后给你第三个结点,也就是值为3的那个结点。那么在你调用你的函数后你的链表应该变成1->2->4.
思路:传统删除链表中某个结点必须记录下一个结点,这样才能将链表重新连接。但这里链表是单向的,从当前准备被删的结点无法追溯到上一个结点。这里可以变通地考虑,既然这个结点是准备要删的,那么这个结点的值就已经无用了。我们就可以把下一个结点的值移到当前结点上,把问题转化为删除下一个结点,即1->2->3->4变成1->2->4->4,再删除第四个结点,变成1->2->4.
/**
* 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;
}
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next