题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
- 记住列表创建得套路。
- 记住cur得用法(每次要从头开始搜索)
- 删列表中元素得时候,cur要指向dummy
- 记住cur 以及 cur->next用来判断时,要注意cur->next为空,且要放到左边
#include<bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x): val(x), next(NULL){
}
};
int main(){
int n,a,b;
while(cin>>n){
cin>>a;
ListNode* dummy_head = new ListNode(-1);//头节点
dummy_head->next = new ListNode(a);
ListNode* cur = dummy_head->next;
//继续完成剩余节点得构建
for(int i = 1; i< n;i++){
cin>>a;
cin>>b;
cur = dummy_head->next;//每次要从第一个开始找
while(cur->val!= b) cur = cur->next;
ListNode* q = cur->next;//
ListNode* p = new ListNode(a);
cur->next = p;
p->next = q;
}
int del;
cin>>del;
//删除
ListNode* cur2 = dummy_head;
//del
while(cur2){
if(cur2->next!=NULL && cur2->next->val==del ){//注意这种前瞻性判断, 且放到左边!!!
cur2->next = cur2->next->next;
}else{
cur2 = cur2->next;
}
}
while(dummy_head->next){
if(dummy_head->next->next==NULL){
cout<<dummy_head->next->val<<endl;
}else{
cout<<dummy_head->next->val<<" ";
}
dummy_head->next = dummy_head->next->next;
}
}
return 0;
}大厂笔试题题解 文章被收录于专栏
主要是公司笔试题得一些总结
