1.栈
插入
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node* next;
Node():next(NULL){}
Node(int _val): val(_val),next(NULL){}
};
void print(Node *head)
{
for(auto p=head;p;p=p->next)
cout<<p->val<<' ';
cout<<endl;
}
int main()
{
Node *top=NULL;
auto a=new Node(1);
a->next=top;
top=a;
auto b=new Node(2);
b->next=top;
top=b;
auto c=new Node(3);
c->next=top;
top=c;
print(top);
}
删除
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node* next;
Node():next(NULL){}
Node(int _val): val(_val),next(NULL){}
};
void print(Node *head)
{
for(auto p=head;p;p=p->next)
cout<<p->val<<' ';
cout<<endl;
}
int main()
{
Node *top=NULL;
auto a=new Node(1);
a->next=top;
top=a;
auto b=new Node(2);
b->next=top;
top=b;
auto c=new Node(3);
c->next=top;
top=c;
print(top);
top=top->next;
delete c;
print(top);
cout<<top->val<<endl;
}
2.队列
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node* next;
Node():next(NULL){}
Node(int _val): val(_val),next(NULL){}
};
void print(Node *head)
{
for(auto p=head;p->next;p=p->next)//如果有下一个元素就输出
cout<<p->val<<' ';
cout<<endl;
}
int main()
{
Node *front=new Node(),*rear=front;
//插入
rear->val=1;
rear->next=new Node();
rear=rear->next;
rear->val=2;
rear=rear->next=new Node();
rear->val=3;
rear=rear->next=new Node();
print(front);
cout<<front->val<<endl;
auto p=front;
front=front->next;
delete p;
print(front);
}