美文网首页LeetCode By Go
[LeetCode By Go 45]237. Delete N

[LeetCode By Go 45]237. Delete N

作者: miltonsun | 来源:发表于2017-08-22 16:17 被阅读4次

这道题目不能用go语言写答案,所以用了C语言

题目

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.

解题思路

删除链表的一个节点本来需要知道该节点的前一个节点,该题目要求的函数要求只知道要删除的节点来做删除
不能删本节点,可以删下一个节点,将下个节点的值赋值给此节点,删除下个节点就行了

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
void deleteNode(struct ListNode* node) {
    if (NULL == node) {
        return;
    }
    
    node->val = node->next->val;
    node->next = node->next->next;
}

相关文章

网友评论

    本文标题:[LeetCode By Go 45]237. Delete N

    本文链接:https://www.haomeiwen.com/subject/jxuldxtx.html