#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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.
分析:此题是给定一个结点(不是尾结点),要删除该结点,可以将该结点后面结点的值拷贝到
当前结点,然后删除该结点后面的一个结点
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
void deleteNode(ListNode* node) {
if(!node)
{
return;
}
//当前结点的后面结点非空,就把当前结点的后面结点的值拷贝到当前结点
//然后删除当前结点的后面结点
if(node->next)
{
node->val = node->next->val;
ListNode* nextNode = node->next->next;
delete node->next;
node->next = nextNode;
}
}
};
void print(vector<int>& result)
{
if(result.empty())
{
cout << "no result" << endl;
return;
}
int size = result.size();
for(int i = 0 ; i < size ; i++)
{
cout << result.at(i) << " " ;
}
cout << endl;
}
void process()
{
vector<int> nums;
int value;
int num;
Solution solution;
vector<int> result;
while(cin >> num )
{
nums.clear();
for(int i = 0 ; i < num ; i++)
{
cin >> value;
nums.push_back(value);
}
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:237. Delete Node in a Linked List
最新推荐文章于 2022-10-13 10:32:50 发布