237 Delete Node in a Linked List 删除链表的结点
编写一个函数,在给定单链表一个结点(非尾结点)的情况下,删除该结点。
假设该链表为1 -> 2 -> 3 -> 4 并且给定你链表中第三个值为3的节点,在调用你的函数后,该链表应变为1 -> 2 -> 4。
详见:https://leetcode.com/problems/delete-node-in-a-linked-list/description/
Java实现:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public void deleteNode(ListNode node) { node.val=node.next.val; node.next=node.next.next; } }
C++实现:
/** * 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) { node->val=node->next->val; ListNode *tmp=node->next; node->next=tmp->next; delete tmp; } };