题目:
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 -> 3 -> 4 ,并且你被给定的节点的值是 3 ,在调用你的函数后链表应该返回 1 -> 2 -> 4 。
思路:
因为题目要求只给定待删除的节点,也就是只有这个节点的值是可以获得和操作的,因此,如果我们用该节点的后一个节点的值来修改这个节点的值,也就是用待删除的节点来代替它后面的一个节点,然后再把后面的所有节点连接起来,就达到了消除给定的节点的目的。直接看代码更容易明白。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
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* temp = node->next;
node->next = temp -> next;
}
};
int main()
{
Solution s;
ListNode* head=new ListNode(0);
ListNode* p = head;
vector<int> nums = { 1,2,3,4,5 };
for (int i = 0; i < nums.size(); i++) {
ListNode* q = new ListNode(nums[i]);
p->next = q;
p = p->next;
}
p->next = NULL;
ListNode* node = head->next->next->next;
//cout << node->val;
s.deleteNode(node);
/*ListNode* result = head->next;
while (result != NULL) {
cout << result->val<<" ";
result = result->next;
}*/
return 0;
}