由了“动态堆栈”思考C

来源:互联网 发布:cctv网络直播电视台 编辑:程序博客网 时间:2024/06/07 11:27

下面是动态堆栈的创建代码:

#include "stdio.h"
struct node
{
    char  data;
    struct  node  *next;
};
struct node *creat()
{
      char ch;
      struct node *head,*r,*p;
      head=NULL;
      while ((ch=getchar())!='/n')
      {
           p=(struct node *)malloc(sizeof(struct node));
           p->data=ch;
           if(head==NULL)
                head=p;
           else
                r->next=p;
           r=p;
      }
      return head;
}
void MakeNull(struct node *s)/*使栈s为空*/
{
        struct node *p=s;
        while(s!=NULL)
        {
            s=s->next;
            free(p);/*释放空间*/
            p=s;
        }
}
Top(struct node *s)
{
    if(s==NULL)/*s为空栈,直接跳出,提示出错信息*/
        printf("The struct node  is empty.");
    else
        return s->data;
}
Pop(struct node *s)
{
        struct node *p;
        if(s==NULL) /*s为空栈,直接跳出,提示出错信息*/
            printf("The stack is empty.");
        else
        {
            p=s;
            s=s->next;
            free(p);
            return s;
        }
}
Push(struct node *s,char x)
{
        struct node *p;
        p=(struct node *)malloc(sizeof(struct node));
        p->data=x;
        p->next=s;
        return p;
}
print(struct node *p)
{
    do
    {
        printf("%c",p->data);
        p=p->next;
    } while(p);
    printf("/n");
}
void main()
{
    struct node *m_stack=creat();
    struct node *p,*r;
    char ch;
    if(m_stack!=NULL)
    {
        p=Push(m_stack,'j');
        print(p);
        r=Pop(m_stack);
        print(r);
        ch=Top(m_stack);
        printf("%c",ch);
    }
    else
    {
        p=Push(m_stack,'j');
        print(p);
    }
    getch();
}

 

所谓栈,其实就是一种特殊的链表,一端开放一端固定。对栈的操作其实就是对链表的操作。对于链表而言,我们可以将两个链表连接、删除链表中的一个节点、插入节点。同样对于栈的操作可以是在栈头加入节点和在栈头删除节点。

 

Push()函数的操作是在栈头加入一个节点:

Push(struct node *s,char x)
{
        struct node *p;
        p=(struct node *)malloc(sizeof(struct node));
        p->data=x;
        p->next=s;
        s=p;
}
这里的s代表的是传递进来栈的第一个节点,我们可以把它看作是一个指针,指向第一个节点的指针。把新节点指向链表然后把该节点放在s盒子中。

 

这个程序老是出问题;虽然能把所想要的东西打印出来了 ,但是总带有“副产品”!高手请指点!

原创粉丝点击