#include<iostream>
using namespace std;
int n,a,v1,v2;
template<typename T>
class LinkList{
private:
struct Node{
T data;
Node *next;
Node(T val): data(val), next(nullptr){}
};
Node *head;
public:
LinkList(): head(nullptr){}
~LinkList(){
while(head){
Node *temp=head;
head=head->next;
delete temp;
}
}
void pushFront(T val) {
Node* newNode = new Node(val);
newNode->next = head;
head = newNode;
}
void pushBack(T val){
Node *newNode=new Node(val);
if(!head){
head=newNode;
return;
}
Node *current=head;
while(current->next){
current=current->next;
}
current->next=newNode;
}
void insertAfter(T targetVal, T newVal){
Node *current = head;
while(current){
if(current->data==targetVal){
Node *newNode= new Node(newVal);
newNode->next=current->next;
current->next=newNode;
return;
}
current = current->next;
}
pushBack(newVal);
}
void checkAfter(T val){
Node *current=head;
while(current){
if(current->data==val){
if(current->next){
cout << current->next->data <<endl;
} else {
cout << "0" << endl;
}
return;
}
current = current->next;
}
cout << "Value " << val << " not found in list" << endl;
}
void removeAfter(T val) {
if (!head) return; // 空链表
Node* current = head;
while (current) {
if (current->data == val) {
Node* temp = current->next;
current->next = current->next->next;
delete temp;
return;
}
current = current->next;
}
}
void print() {
Node* current = head;
while(current) {
cout << current->data << " -> ";
current = current->next;
}
cout << "nullptr" << endl;
}
};
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
LinkList<int> mylist;
mylist.pushFront(1);
cin>> n;
for(int i=1;i<=n;i++){
cin >> a;
if(a==1){
cin >> v1 >> v2;
mylist.insertAfter(v1,v2);
}else if(a==2){
cin >> v1;
mylist.checkAfter(v1);
}else{
cin >> v1;
mylist.removeAfter(v1);
}
}
}
c++ 链表类简易模板
移动端可扫我直达哦~
本文作者:Alphonse
本文链接:c++ 链表类简易模板 - https://www.abddb.com/1223.html
版权声明:如博文中无特别声明,即为站长原创文章,仅代表个人观点,版权归 小鸟数据 所有,如需转载,烦请注明出处!