借助栈来实现但链表上的逆置,我已编好就是有一个错找不出

来源:百度知道 编辑:UC知道 时间:2024/05/22 18:26:16
int stack[50];
int top=0;
struct rec
{
int num;
struct rec *next;
}
int pop()
{
if (top>0)
return (stack[--top]);
else
return (0);
}
void push(struct rec *p)
{
if (top<50)
stack[top++] = p->num;
}
struct rec *biao()
{struct rec *head,*p,*q;
int i,m;
p=(struct rec*)malloc(sizeof(struct rec));
head=p;
for(i=0;i<5;i++)
{
q=(struct rec*)malloc(sizeof(struct rec));
scanf("%d",&m);
q->num=m;q->next='\0';
p->next=q;p=q;
}
return(head);
}
main()
{
struct rec *head;
head=biao();
push(head);
while (top)
printf("%d",pop());
}

push(head);
这里错了。首先head是一个空节点,里面什么都没装,只是为了标记链表的头。head->num没有被给值。输入的5个数是从head->next->num开始记录的。
其次,要想把整个表逆过来,不能只压栈一个元素,要把整个表里的所有元素依次压进去,再弹出来。修改后代码:(经TURBOC调试通过)

#include<malloc.h>
#include<stdio.h>
int stack[50];
int top=0;
struct rec
{
int num;
struct rec *next;
};
int pop()
{
if (top>0)
return (stack[--top]);
else
return (0);
}
void push(struct rec *p)
{
if (top<50)
stack[top++] = p->num;
}
struct rec *biao()
{struct rec *head,*p,*q;
int i,m;
p=(struct rec*)malloc(sizeof(struct rec));
head=p;
for(i=0;i<5;i++)
{
q=(struct rec*)malloc(sizeof(struct rec));
scanf("%d",&m);
q->num=m;
q->next=NULL;
p->next=q;
p=q;
}
return(head);
}

main()
{
struct rec *head, * p;
head=biao();
p=head->next;
w