[容易]在O(1)时间复杂度删除链表节点
题目来源:http://www.lintcode.com/zh-cn/problem/delete-node-in-the-middle-of-singly-linked-list/
这题主要是题意一开始不明白,举个例子:
8->6->3->1->9->2->null, 1
输出
8->6->3->9->2->null
传入的是要删除节点的地址。
方法是,将删除节点下个节点的值赋给本节点,再将下一节点删除。
题目说删除的不能是表头和表尾,但是数据测试了一下,只是不能是表尾。
8->6->3->1->9->2->null, 2
输出
8->6->3->1->9->2->null
1 /**
2 * Definition of ListNode
3 * class ListNode {
4 * public:
5 * int val;
6 * ListNode *next;
7 * ListNode(int val) {
8 * this->val = val;
9 * this->next = NULL;
10 * }
11 * }
12 */
13 class Solution {
14 public:
15 /**
16 * @param node: a node in the list should be deleted
17 * @return: nothing
18 */
19 void deleteNode(ListNode *node) {//把下个节点的值赋值给本节点,把下个节点删除,相当于删除了本节点
20 // write your code here
21 if(node==NULL||node->next==NULL) return;
22 ListNode *next=node->next;
23 node->val=next->val;
24 node->next=next->next;
25 return;
26 }
27 };
-------------------------------------------------
原创博客 转载请注明出处http://www.cnblogs.com/hslzju
-------------------------------------------------