码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构---栈的链表实现

时间:2014-07-29 15:16:28      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:   链表   数据结构   先进后出   

栈的链表实现C代码如下:

#include <stdio.h>

typedef int ElemType;


typedef struct node
{
    ElemType Data;
    struct node *next;
}Node;

typedef struct stack
{
    Node *top;
}Stack;

//初始化栈
void InitStack(Stack *S)
{
    S->top=NULL;
}

//入栈
int PushStackValue(Stack *S)
{
    printf("Input the Value of stack member:\n(0-exit)\n");
    int value;
    int i=1;
    Node *NewNode=(Node *)malloc(sizeof(Node));
    printf("Please input the %dst value of stack:\n",i);
    scanf("%d",&value);
    NewNode->Data=value;
    NewNode->next=S->top;
    S->top=NewNode;
    i++;
    while(value)
    {
        Node *NewNode=(Node *)malloc(sizeof(Node));
        printf("Please input the %dst value of stack:\n",i);
        scanf("%d",&value);
        if(value!=0)
            i++;
        NewNode->Data=value;
        NewNode->next=S->top;
        S->top=NewNode;
    }
    S->top=S->top->next;
    return i-1;
}

//出栈
int PopStackValue(Stack *S,int len)
{

    if(len>0)
    {
        printf("the stack %dst value pop out: %d\n",len,S->top->Data);
    }
    else
    {
        printf("The Stack is empty\n");
    }
    len--;
    S->top=S->top->next;
    return len;
}

//判断栈空
void IsEmpty(Stack *S)
{
    if(S->top==NULL)
    {
        printf("The Stack is empty.\n");
    }
    else
    {
        printf("The stack is not empty.\n");
    }
}


//清空栈
void ClearStack(Stack *S)
{
    S->top=NULL;
}

//遍历栈
Stack * ScanStack(Stack *S)
{
    Stack *Temp=S;
    printf("The all stack member(from top to bottom) is:\n");
    while(S->top!=NULL)
    {
        printf("%d ",S->top->Data);
        S->top=S->top->next;
    }
    printf("\n");

    return Temp;
}

void main()
{
    Stack *S=(Stack *)malloc(sizeof(Stack));
    int len;

    InitStack(&S);
    len=PushStackValue(&S);
    len=PopStackValue(&S,len);
    len=PopStackValue(&S,len);
    S=ScanStack(&S);
    IsEmpty(&S);
}

运行结果:

bubuko.com,布布扣




转载请注明作者:小刘

数据结构---栈的链表实现,布布扣,bubuko.com

数据结构---栈的链表实现

标签:   链表   数据结构   先进后出   

原文地址:http://blog.csdn.net/u013018721/article/details/38266661

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!