鏈式棧和鏈式佇列--簡單易懂
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int datatype;
typedef struct link_node{
datatype info;
struct link_node*next;
}node;
node *init()
{
return NULL;
}
int empty(node *top)
{
return top?0:1;
}
datatype read(node *top)
{
if(!top)
{
cout << "棧空" << endl;
exit(1);
}
return top->info;
}
void display(node *top)
{
node *p;
p = top;
if(!p) cout << "鏈式棧為空" << endl;
while(p)
{
cout << p->info;
p = p->next;
}
}
node* push(node *top,datatype x)
{
node *p;
p = new struct link_node();
p->info = x;
p->next = top;
top = p;
return top;
}
node *pop(node *top)
{
node* p;
if(!p)
{
cout << "鏈式棧為空" << endl;
return NULL;
}
p = top;
top = top->next;
delete p;
return top;
}
void recycle(node *top) //用來刪除動態申請記憶體
{
node *p = top;
if(!p)
exit(1);
while(top)
{
p = top;
top = top->next;
delete p;
}
}
int main()
{
node *top ;
top = init();
top = push(top,1);
top = push(top,2);
top = push(top,3);
top = push(top,4);
display(top);
cout << "棧頂為:" << read(top) << endl;
recycle(top);
return 0;
}
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int datatype;
typedef struct link_node{
datatype info;
struct link_node*next;
}node;
typedef struct
{
node*front,*rear; //佇列的隊首和隊尾指標,指向第一個和最後一個佇列成員
}queue;
queue*init()
{
queue *qu;
qu = new queue();
qu->front = qu->rear = NULL;
return qu;
}
int empty(queue qu)
{
return qu.front?0:1;
}
void display(queue *qu)
{
node *p = qu->front;
if(!p) cout << "隊空" << endl;
while(p)
{
cout << p->info << endl;
p = p->next;
}
}
queue*insert(queue*qu,datatype x)
{
node*p;
p = new node();
p->info = x;
p->next = NULL;
if(!qu->front)
qu->front = qu->rear = p;
else
{
qu->rear->next = p;
qu->rear = p;
}
return qu;
}
datatype read(queue *qu)
{
if(!qu->front){ cout << "隊空" << endl;exit(1); }
return qu->front->info;
}
queue *del(queue *qu)
{
node *p;
if(!qu->front) { cout<<"無法刪除"<<endl;return qu;}
p = qu->front; //指向隊首
qu->front = p->next; //隊首指標指向下一個結點
delete p;//用free來沒報錯,奇怪
if(!qu->front) qu->rear = NULL; //佇列中唯一元素被刪除後,佇列為空
return qu;
}
void recycle(queue *qu) //用來刪除動態申請記憶體
{
node *p,*q;
q = p = qu->front;
delete qu; //qu結點一定存在,故先刪除
if(!p)
exit(1);
while(q)
{
p = q; //儲存一個臨時結點,以便用來刪除
q = q->next;
delete(p);
}
}
int main()
{
queue *qu;
qu = init();
insert(qu,1);
insert(qu,2);
insert(qu,3);
insert(qu,4);
display(qu);
cout << "隊首為:" << read(qu) << endl;
recycle(qu);
return 0;
}