您的位置:首页 > 理论基础 > 数据结构算法

传说中的数据结构(用的链表)

2014-01-16 10:20 302 查看
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

struct node

{

    int data;

    struct node *next;

};

int main()

{

    int n,i;

    char ml[10];

    struct node *head,*p,*q;

    head=(struct node*)malloc(sizeof(struct node));

    head->next=NULL;

    while(scanf("%d",&n)!=EOF)

    {

        for(i=0;i<n;i++)

        {

            scanf("%s",ml);

            if(strcmp(ml,"push")==0)

            {

                p=(struct node*)malloc(sizeof(struct node));

                scanf("%d",&p->data);

                p->next=head->next;

                head->next=p;

            }

            else if(strcmp(ml,"pop")==0)

            {

                if(head->next==NULL)printf("erroe\n");

                else

                {

                    q=head->next;

                    head->next=q->next;

                    free(q);

                    p=head->next;

                }

            }

            else if(strcmp(ml,"top")==0)

            {

                if(head->next==NULL)

                    printf("empty\n");

                else printf("%d\n",p->data);

            }

        }

        while(head->next!=NULL)

        {

            q=head->next;

            head->next=q->next;

            free(q);

        }

  p=head->next;

  while(p)

  {

   printf("%d ",p->data);

   p=p->next;

  }

        if(i==n)

        printf("\n");

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: