题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
struct Node{
int val;
Node* next;
Node(int new_val, Node* ptr=nullptr){
this->val = new_val;
this->next = ptr;
}
};
void showList(Node* head){
Node* ptr = head;
while(ptr){
cout << ptr->val << " ";
ptr = ptr->next;
}
cout << endl;
}
int main() {
Node* head = nullptr;
int nodeNum, headVal = 0;
cin >> nodeNum >> headVal;
vector<pair<int, int> > store;
for(int i = 0; i < (nodeNum-1); i ++){
int insertVal, indVal = 0;
cin>>insertVal>>indVal;
store.push_back(make_pair(insertVal, indVal));
}
int delVal = 0;
cin>>delVal;
// 链表插入,当前节点A为被插入节点时,创建新节点B,B->next=A->next,A->next = B
head = new Node(headVal);
int count = 0;
Node* ptr = head;
while(count < nodeNum-1){
int insertVal = store[count].first;
int indVal = store[count].second;
int nowVal = ptr->val;
if(nowVal == indVal){
Node* newNode = new Node(insertVal);
newNode->next = ptr->next;
ptr->next = newNode;
count++;
ptr = head;
// continue;
}else{
ptr = ptr->next;
}
}
// showList(head);
/* 删除节点,
1. 当删除节点为表首节点head:
head=ptr->next,
新建指针del指向ptr,重新设置ptr=head, 之后删除del
2. 删除节点不是表首节点,则判断当前节点的下一个节点是不是待删除节点
3. 最后,遍历到下一个节点为nullptr,此时说明到表尾节点了。
结束删除
*/
ptr = head;
while(ptr){
int nowVal = ptr->val;
if(ptr == head && nowVal == delVal){
head = ptr->next;
Node* del = ptr;
ptr = head;
del->next = nullptr;
delete del;
}else if( ptr->next ){
Node* next = ptr->next;
int nextVal = next->val;
if(nextVal == delVal){
ptr->next = next->next;
next->next = nullptr;
ptr = ptr->next;
delete next;
}else{
ptr = ptr->next;
}
}else{
break;
}
}
showList(head);
}
// 64 位输出请用 printf("%lld")
查看29道真题和解析
