我用堆栈对单链表就地逆置,没报错,但程序无法成功运行
我的基本思想是:顺序堆栈储存链表中指向每个节点的指针。依次进栈后再顺序出栈,连接在链表的头结点后。问题见代码中注释。
程序代码://实现函数
int reverseByStack(SLNode *head) //SLNode是定义的单链表节点的结构体
SeqStack tempStack; //SeqStack是定义的顺序堆栈的结构体,其中数组为指向SLNode类型的指针数组,存储指向每个节点的指针
SLNode *tempList,*d,*p;
ListInitiate(&tempList); //初始化函数,初始化单链表,下同
tempList=head;
while(tempList->next!=NULL) //进栈
{
if(StackPush(&tempStack,tempList->next)==0)
{
printf("error!\n");
return 0;
}
tempList=tempList->next;
}
//就是这个while循环部分开始出错,StackPush函数见下,难道是参数传递问题?
ListInitiate(&p);
p=head;
while(StackNotEmpty(tempStack)) //出栈
if(StackPop(&tempStack,&d)==1)
{
p->next=d;
p=p->next;
}
p->next=NULL;
return 1;
}
//定义堆栈的结构体变量
typedef struct
{
SLNode *stack[MaxStackSize];
int top;
}SeqStack;
//入栈函数
int StackPush(SeqStack *S,SLNode *x)
{
if(S->top>=MaxStackSize)
{
printf ("堆栈已满!\n");
return 0;
}
else
{
S->stack[S->top]=x;
S->top++;
return 1;
}
}
//出栈函数
int StackPop(SeqStack *S,SLNode **d) //
{
if(S->top<=0)
{
printf("堆栈已空!\n");
return 0;
}
else
{
S->top--;
*d=S->stack[S->top];
return 1;
}
}
编译时没有报错,但运行时就显示:程序已停止运行。
不知道该如何改正,请大家指教!
[ 本帖最后由 xyaliner 于 2012-10-29 21:01 编辑 ]








