链栈问题,请问错在哪?
#include <stdio.h>
typedef struct stack
{
int data;
struct stack *next;
}node;
node *h;
node *initialize()
{
h=(node *)malloc(sizeof(node));
h-> next=NULL;
return h;
}
push(node *h)
{
node *p;
int x;
scanf( "%d ",&x);
while(x!=-1)
{
p=(node *)malloc(sizeof(node));
p-> data=x;
p-> next=h;
h=p;
scanf( "%d ",&x);
}
while(1);
}
pop(node *h)
{
if (h==NULL)
printf( "error ");
else
{
while(h!=NULL)
{
printf( "%d ",h-> data);
h=h-> next;
}
}
}
void main()
{
/* node *h; */
/*int i;*/
/*char x;*/
h=initialize();
/*scanf( "%c ",&x); */
push(h);
pop(h);
printf( "\n ");
getch();
}
[解决办法]
push(node *h)
函数试图改变h本身,应该传入指针的地址,即应该
push(node **h)
[解决办法]
对,指针的指针
否则的出了函数就不对了
原来的值就不存在了
[解决办法]
#include <iostream.h>
#include <malloc.h>
#define NULL 0
typedef struct snode
{
int data;
struct snode *next;
}stack;
//
void push( stack **s,int x)
{
stack *p;
p=( stack *)malloc(sizeof(snode));
//cin> > x;
p-> data=x;
p-> next=*s;
*s=p;
}
//
void pop( stack **s )
{
stack *p;
int e = 0 ;
p=(stack *)malloc(sizeof(snode));
if(NULL == (*s))
cout < < "空战 ";
else
{
p=*s;
e=p-> data;
*s=p-> next;
cout < < "出栈的数是:\t " < <e < <endl ;
}
free(p);
}
//
void print(stack **s)
{
//stack *s;
if( *s == NULL)
cout < < "空栈 ";
else if((*s)!=NULL)
{
cout < < "出栈的数是:\t " < <(*s)-> data < <endl ;
*s = (*s)-> next;
}
}
//
void stackempty(stack **s)
{
//stack *s;
if(*s == NULL)
cout < < "栈空 " < <endl ;
else
cout < < "栈非空 " < <endl ;
}
//
void main()
{
stack *s= NULL ;// = new stack();
int f,x,e;
puts( "输入1(入栈)或2(出栈)\n ") ;
cin> > f;
while(1)
{
switch (f)
{
case 1:
puts( "输入入栈的数:\t ") ;
cin> > x;
push(&s,x);
print(&s);
stackempty(&s);
break;
case 2:
pop(&s);
print(&s);
stackempty(&s);
break;
default:
break ;
}
break ;
}
system( "pause ") ;
}
[解决办法]
#include <stdio.h>
#include <stdlib.h>
typedef struct stack
{
int data;
struct stack *next;
}node;
node *h;
node *initialize()
{
h=(node *)malloc(sizeof(node));
h = NULL;
return h;
}
node *push(node *h)
{
node *p;
int x;
scanf( "%d ",&x);
while(x != -1)
{
p=(node *)malloc(sizeof(node));
p-> data=x;
p-> next=h;
h=p;
scanf( "%d ",&x);
}
return h;
}
void pop(node *h)
{
if (h==NULL)
printf( "error ");
else
{
while( h != NULL)
{
printf( "%d ",h-> data);
h = h-> next;
}
}
}
void main()
{
node *h;
h=initialize();
h = push(h);
pop(h);
printf( "\n ");
getch();
}