注册 登录
编程论坛 数据结构与算法

链栈异常

cwl168 发布于 2013-01-14 20:46, 343 次点击
#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)
{
   s->top=(Node *)malloc(sizeof(Node));
   s->base=s->top;

   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;
}
3 回复
#2
不玩虚的2013-01-14 22:17
好好学习啦,我回家了,没网了,,祝你好运,有机会回家了一起学习啦
#3
azzbcc2013-01-15 09:23
程序代码:
#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)
{
    s->top=(Node *)malloc(sizeof(Node));
    s->base=s->top;

    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;
}
#4
azzbcc2013-01-15 09:26
你这个不好,没有free,再写个释放空间的Destroy函数。。。
1