DAY 6
48.从单向链表中删除指定值的节点
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode():val(0),next(nullptr){}
ListNode(int x):val(x),next(nullptr){}
ListNode(int x,ListNode* next):val(x),next(next){}
};
int main() {
int n,val;
while(cin>>n){
cin>>val;
//由于要删除节点,所以要设置一个虚拟头节点
auto* dummy_head=new ListNode(-1);
auto* head=new ListNode(val);
dummy_head->next=head;//让虚拟头节点指向真实头节点
vector<int> nums(2*n-2,-1);
for(int & num : nums){
cin>>num;
}
int deleteNum;
cin>>deleteNum;
//输入部分完毕
for(int i=0;i<nums.size();i+=2){
auto* node=new ListNode(nums[i]);
auto* cur=dummy_head;
while(cur->val!=nums[i+1]){
cur=cur->next;
}
//此时cur指向要被插入的节点
//此时进行判断,如果是最后的一个节点,直接插即可;
if(cur->next==nullptr) cur->next=node;
else{
//先把cur->next存下来
ListNode* temp=cur->next;
cur->next=node;
node->next=temp;
}
}
//再让cur指向虚拟头节点,因为要删除节点,所以有个虚拟头节点方便点
auto* cur=dummy_head;
while(cur->next->val!=deleteNum){
cur=cur->next;
}
cur->next=cur->next->next;
cur=head;
while(cur!=nullptr){
cout<<cur->val<<" ";
cur=cur->next;
}
}
}
51.输出单向链表中倒数第k个结点
ACM模式的构造链表
方法的话双指针,快的先走k步;直到快的为空的时候,慢指针指向倒数第k个节点。
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode():val(0),next(nullptr){}
ListNode(int x):val(x),next(nullptr){}
ListNode(int x,ListNode* next):val(x),next(next){}
};
int nodeVal(ListNode* node,int k){
ListNode* fast=node;
ListNode* slow=node;
for(int i=0;i<k;i++){
fast=fast->next;//fast先走k步
}
while(fast!=nullptr){
fast=fast->next;
slow=slow->next;
}
return slow->val;
}
int main() {
int count_node;
int val;
int k;
while(cin>>count_node){
auto* head=new ListNode(-1);
ListNode* p=head;
for(int i=1;i<=count_node;i++){
cin>>val;
auto* tmp=new ListNode(val);
p->next=tmp;
p=tmp;
}
cin>>k;
int res=0;
if(k>=1) res=nodeVal(head->next,k);
cout<<res<<endl;
}
}