【leetcode 237】 Delete Node in a Linked List (C++)

来源:互联网 发布:vlan arp 获得保存mac 编辑:程序博客网 时间:2024/04/29 23:01

题目

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.

即编写一个程序,删除单链表中的一个给定结点(尾部除外)

原题链接


思路

1,由于结点直接给出,所以只需要将其后续结点的值赋予自身,再删除其后续结点。

2,把后续结点(其val与next)直接赋给所给结点,然后释放后续结点存储空间。


代码

C++class Solution{public:    void deleteNode(ListNode* node){        if(node==NULL) return;        node->val=node->next->val;        node->next=node->next->next;    }};

or

C++class Solution{public:    void deleteNode(ListNode* node){        if(node==NULL) return;        ListNode* p=node->next;        *node=*p;         free(p);    }};

1 0
原创粉丝点击