欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

237. Delete Node in a Linked List

程序员文章站 2024-02-17 10:40:52
...

Problem

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

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.

Solution

传统的解决方式需要我们知道链表的头节点,这里采用了一个巧妙的方法,将待删除的节点后的节点A赋值给它,再按常规方法删除节点A

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        ListNode *p;
        p=node->next;
        node->val=p->val;
        node->next=p->next;
        free(p);
    }
};
相关标签: easy