首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

一个栈的链表实现的有关问题

2012-04-18 
一个栈的链表实现的问题。#includestdlib.h#includeiostream.hstruct stack{int datastruct stack * n

一个栈的链表实现的问题。
#include<stdlib.h>
#include<iostream.h>
struct stack
{
int data;
struct stack * next;
};
int main()
{  
bool empty(stack *);
void push(int,stack *);
stack * pop(stack *);
int n;
stack T;
stack * R=&T;
R->next=NULL;
stack * G;
cout<<"please input data:\n";
cin>>n;
push(n,R);
cout<<"please input data:\n";
cin>>n;
push(n,R);
cout<<"pop stack:\n";
G=pop(R);
cout<<G->data<<"\n"
<<"pop stack:\n";
G=pop(R);
cout<<G->data<<"\n";
cout<<"please input data:\n";
cin>>n;
push(n,R);
cout<<"pop stack:\n";
G=pop(R);
cout<<G->data<<"\n";
cout<<"please input data:\n";
cin>>n;
push(n,R);
cout<<"please input data:\n";
cin>>n;
push(n,R);
cout<<"please input data:\n";
cin>>n;
push(n,R);
cout<<"please input data:\n";
cin>>n;
push(n,R);
cout<<"please input data:\n";
cin>>n;
push(n,R);
cout<<"pop stack:\n";
G=pop(R);
cout<<G->data<<"\n";
cout<<"pop stack:\n";
G=pop(R);
cout<<G->data<<"\n";
cout<<"pop stack:\n";
G=pop(R);
cout<<G->data<<"\n";
cout<<"pop stack:\n";
G=pop(R);
cout<<G->data<<"\n";
cout<<"pop stack:\n";
G=pop(R);
cout<<G->data<<"\n";
return 0;
}
void push(int x,stack * S)
{

while(S->next!=NULL)
S=S->next;
stack * q=(stack *)malloc(sizeof(stack));
q->data=x;
q->next=NULL;
S->next=q;
}
bool empty(stack * S)
{
if(S->next)
return false;
else
return true;
}
//1 与2效果等同
stack * pop(stack * S)
{
if(empty(S))
{
cerr<<"the stack is empty!\n";
exit(0);
}
stack * q;
while(S->next!=NULL)
{
q=S;
S=S->next;
}
q->next=NULL;
return S;
}
//2
/*stack * pop(stack * S)
{
stack * q;
stack * K=S;
stack * T;
while(S->next!=NULL)
{
q=S;
S=S->next;
}
T=S;
q->next=NULL;
S=K;
return T;
}*/
我感觉1是不对的,2才是对的,但是它又是对的,为什么?

[解决办法]
栈是只能从一端插入和删除的,你要明白并把握与线性表的不同

热点排行