#2
crystall2012-12-22 10:10
程序代码: #include<stdio.h> #include<stdlib.h> #include<malloc.h> typedef struct Node { int data; struct Node * next; }Node; typedef struct Stack { Node * top; Node * base; }Stack; void Inti(Stack *s) { //Node *N=(Node *)malloc(sizeof(Node)); s->base = s->top = NULL; //s->top->next = NULL;//这里必须是s->top->next=NULL; printf("Inti Success!\n"); } void Push(Stack *s,int e) { Node *p=(Node*)malloc(sizeof(Node)); p->data = e; if((s->top == NULL) && (s->base == NULL)) { s->base = s->top = p; } else { s->top->next = p; s->top = p; } s->top->next = NULL; //p->data=e;p->next=s->top->next; //s->top=p; printf("Push Success!\n"); } void print(Stack *s) { //以前比如是 目前桟中的元素 //5 //4 //3 //2 //1 //s->base->data = 1; //s->base->next = 数据为2的地址 //s->top->data = 5; //s->top->next = ? s->top 已经是最后栈顶了,你再继续往后遍历是不行的。 //要遍历输出,按照你的这个程序,只能从 栈底base开始往后遍历。 Node * p = s->base; if(s->top==s->base) { printf("The stack is empty!\n"); } while (p) { printf("%d\n", p->data); p = p->next; } printf("\n"); return; } int main() { Stack *s; s=(Stack *)malloc(sizeof(Stack)); Inti(s); Push(s,1); Push(s,2); Push(s,3); Push(s,4); Push(s,5); print(s); return 0; } |
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Node
{
int data;
struct Node * next;
}Node;
typedef struct Stack
{
Node * top;
Node * base;
}Stack;
void Inti(Stack *s)
{
Node *N=(Node *)malloc(sizeof(Node));
s->base=s->top=N;
s->top->next=NULL;//这里必须是s->top->next=NULL;
printf("Inti Success!\n");
}
void Push(Stack *s,int e)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=e;p->next=s->top->next;
s->top=p;
printf("Push Success!\n");
}
void print(Stack *s)
{
Node * p = s->top;
if(s->top==s->base)
{
printf("The stack is empty!\n");
}
while (p !=s->base)
{
printf("%d\n", p->data);
p =p->next;
}
printf("\n");
return;
}
int main()
{
Stack *s;
s=(Stack *)malloc(sizeof(Stack));
Inti(s);
Push(s,1);
Push(s,2);
Push(s,3);
Push(s,4);
Push(s,5);
print(s);
return 0;
}
为什么遍历不出来?