关于用单链表实现栈结构

  栈是一种先进后出的数据结构,这里便不过多赘述。栈可以用数组实现,也可以用单链表实现。如果使用数组栈虽然比较方便但是由于数组大小是固定的,会造成一些问题。如果用单链表(从头部插入)实现栈结构,会比数组栈好一些。这里有一道数据结构水题http://helloc.openjudge.cn/xl/040/,就通过这个题来总结一下自己的学习成果。先直接上代码,代码如下:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct  node{
    int data;
    struct node*next;
}stack,*linkstack;
int pd(char *s)
{
    if(strcmp(s,"push")==0)
    return 1;
    else return 0;
}
linkstack push(int t,stack*h)
{
    stack *p;
    p=(linkstack)malloc(sizeof(stack));
    p->data=t;
    p->next=h;
    return p;
}
linkstack pop(stack*h,int *flag)
{
    if(h->next==NULL)
    {
    *flag=0;
    return h;
    }
    else
    {
        stack*p;
        p=h->next;
        free(h);
        return p;
    }
}
void f(stack *h)
{
    if(h->next==NULL)
    return;
    else
    {
        f(h->next);
        printf("%d ",h->data);
    }
}
int main()
{
    int n,i,t,l,temp,flag;
    char s[10];
    scanf("%d",&t);
    for(l=0;l<t;l++)
    {
        stack *h;
        flag=1;
        h=(linkstack)malloc(sizeof(stack));
        h->next=NULL;
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
            scanf("%s",s);
            if(pd(s))
            {
                scanf("%d",&temp);
                if(flag!=0)
                h=push(temp,h);
            }
            else
            {
            if(flag!=0)
            h=pop(h,&flag);
            }
        }
        if(flag==0)
        printf("error");
        else
        {
            f(h);
        }
        printf("\n");
    }
    return 0;
}
View Code

先定义一个结构体,定义如下:

typedef struct  node{
    int data;//存放数据
    struct node*next;//指向下一个结点
}stack,*linkstack;//linkstack就相当于struck node*,stack相当于struck node

申请一个头结点,并使头结点指向的下一个结点为空:

stack *h;
h=(linkstack)malloc(sizeof(stack));//申请一个头结点,头结点不存放任何数据,但头结点并不为NULL
h->next=NULL;//使头结点的next指向为空

当输入push时:

linkstack push(int t,stack*h)
{
    stack *p;
    p=(linkstack)malloc(sizeof(stack));//申请一个结点空间
    p->data=t;//存放数据
    p->next=h;//使该节点指向头结点
    return p;//返回一个结构体指针,用于改变头指针指向;
}

当输入pop时:

linkstack pop(stack*h,int *flag)
{
    if(h->next==NULL)//如果当前头结点的next为空,说明栈已空
    {
    *flag=0;
    return h;
    }
    else
    {
        stack*p;
        p=h->next;//使p指向当前头结点h指向的下一个结点啊
        free(h);//释放内存
        return p;
    }
}

然后通过递归输出栈内元素:

void f(stack *h)
{
    if(h->next==NULL)//当h指向的next为空时,说明栈已空
    return;
    else
    {
        f(h->next);
        printf("%d ",h->data);
    }
}

 

posted on 2018-01-26 12:45  laplus  阅读(1562)  评论(0编辑  收藏  举报

导航