问题描述
- 关于栈的链式结构,请问以下代码问题在哪?
-
#include
#include
struct node
{
int data;
struct node next;
};
struct node *createemptystack_link(void)
{
struct node *top;
top=(struct node)malloc(sizeof(struct node));
if(top!=NULL)
top->next=NULL;
else
printf("out of space!");
return top;
}
int isemptystack_link(struct node top)
{
return (top==NULL);
}
void push_link(struct node *top,int x)
{
struct node *p;
p=(struct node)malloc(sizeof(struct node));
if(p==NULL)
printf("out of space!");
else
{
p->data=x;
p->next=top;
top=p;
}
}
void pop_link(struct node *top)
{
struct node *p;
if(top==NULL)
printf("empty stack pop!");
else
{
p=top;
top=top->next;
free(p);
}
}
int main()
{
struct node *createemptystack_link(void);
void push_link(struct node *top,int x);
void pop_link(struct node *top);
int isemptystack_link(struct node *top);
int i,n,x;
struct node *p;
p=createemptystack_link();
printf("请输入入栈数据的个数:");
scanf("%d",&n);
printf("请输入数据:");
for(i=0;i
{
scanf("%d",&x);
push_link(p,x);
}
while(p)
{
printf("%d",p->data);
pop_link(p);
}
return 0;
}
从测试各函数来看,是创建链表或入栈地方有错。
解决方案
用VS2013编译通过
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *pre;
struct node *next;
};
struct node *p = NULL;
int isemptystack_link()
{
return p->pre == NULL;
}
void push_link(int x)
{
if (p == NULL)
{
p = (struct node*)malloc(sizeof(struct node));
p->data = x;
p->pre = NULL;
p->next = NULL;
}
else
{
struct node *pp = p;
p = (struct node*)malloc(sizeof(struct node));
p->data = x;
p->pre = pp;
pp->next = p;
p->next = NULL;
}
}
void pop_link()
{
if (p == NULL)
printf("empty stack pop!");
else
{
p = p->pre;
if (p != NULL)
free(p->next);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int i, n, x;
printf("num");
scanf_s("%d", &n);
printf("data");
for (i = 0; i<n; i++)
{
scanf_s("%d", &x);
push_link(x);
}
while (p != NULL)
{
printf("%dn", p->data);
pop_link();
}
return 0;
}
解决方案二:
你的代码错得太多,你没有指向前继节点的指针,怎么能出栈呢?
解决方案三:
struct node
{
int data;
struct node next; //此处应该用指针类型
};
p=(struct node)malloc(sizeof(struct node));//强制转换应该转换为指针类型
int isemptystack_link(struct node top) //判断栈是否为空,应该是判断top->next==NULL
{
return (top==NULL);
}
p=(struct node)malloc(sizeof(struct node)); //同上
p->data=x;
p->next=top; //节点插入出错,链表的头部插入应该是插到头结点的后方
top=p;
应该改为 p->next = top->next; top->next = p;
if(top==NULL) //同上
p=top;
top=top->next;
free(p); //改为p = top->next;top->next = top->next->next;free(p);
错误太多,目测对链栈的理解太浅,多读读书在实践吧!
时间: 2024-11-03 21:09:19