给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。
1.此题对比原题有改动
2.题目保证链表中节点的值互不相同
3.该题只会输出返回的链表和结果做对比,所以若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点
数据范围:
0<=链表节点值<=10000
0<=链表长度<=10000
示例1
输入:
{2,5,1,9},5
返回值:
{2,1,9}
复制
说明:
给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 2 -> 1 -> 9
示例2
输入:
{2,5,1,9},1
返回值:
{2,5,9}
说明:
给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 2 -> 5 -> 9
- 思路
输入链表,找到链表里的值,更改指针
- 具体实现
#include<iostream>
using namespace std;
//定义链表
typedef struct LNode
{
int data;
struct LNode* next;
LNode(int val) :data(val), next(nullptr) {};//构造函数
}LNode,*LinkList;
//创建链表
LinkList ListTailInsert(LinkList &L)
{
LNode* dummyHead = new LNode(-1), * r = dummyHead, * s;
int x;
while (cin>>x&&x!=9999)
{
s = new LNode(x);
r->next = s;
r = s;
}
return dummyHead;
}
//删除节点
class Solution {
public:
LNode* deleteNode(LNode* head, int n) {
LNode* dummyHead = new LNode(-1);
dummyHead->next = head; //表头加入虚拟头节点
LNode* cur = dummyHead; //遍历指针,表示当前待判断节点的前驱节点
while (cur->next) {
if (cur->next->data == n) cur->next = cur->next->next;
else cur = cur->next;
}
return dummyHead->next;
}
};
int main()
{
LinkList L = ListTailInsert(L);
int n;
cout << "输入节点:";
cin >> n;
Solution s1;
s1.deleteNode(L,n);
LNode* cur = L->next;
cout << "删除节点后链表:";
while (cur)
{
cout << cur->data << " ";
cur = cur->next;
}
return 0;
}