数据结构-栈(C语言)

/* 
    数据结构-栈(C语言)  
    功能:建栈、出栈、压栈、判断栈是否为空、  
*/  
  
#include <stdio.h>   
#include <malloc.h>  
#define Ele int  
  
  
  
typedef struct _Stack  
{  
    Ele data;  
    struct _Stack* next;  
} Stack;  
  
Stack * NewStack();//初始化栈   
int Push(Stack * S, Ele value) ;//压栈   
int Pop(Stack * S);//出栈   
void Traserval(Stack *S);//遍历   
int IsEmpty(Stack * S);//是否为空   
  
int main()  
{  
    int i = 0;  
    Stack* S = NewStack();  
    for(i = 0; i < 20; i++)  
    {  
        Push(S, i * 3);//压栈   
    }  
    Traserval(S);  
    for(i = 0; i < 25;i++)  
    {  
        printf("是否为空 :%d    ", IsEmpty(S));   
        printf("出栈: %d\n", Pop(S));  
    }   
      
    return 0;  
}  
//初始化栈  
Stack * NewStack()  
{  
    Stack* S = (Stack*)malloc(sizeof(Stack));  
    S->next = NULL;  
    S->data = 0;  
    return S;  
 }   
   
//压栈  
int Push(Stack * S, Ele value)   
{  
    Stack* temp = NewStack();  
    if(temp == NULL)  
    {  
        return -1;  
    }  
    temp->data = value;  
    temp->next = S->next;  
    S->next = temp;  
    return 1;  
}  
//出栈   
Ele Pop(Stack * S)  
{  
    Stack * temp;  
    Ele data;  
      
    if(S->next == NULL)  
    {  
        return data;  
    }  
    temp = S->next;  
    data = temp->data;  
    S->next = temp->next;  
    free(temp);  
    return data;  
}  
//是否为空   
int IsEmpty(Stack * S)  
{  
    if(S->next == NULL)  
    {  
        return 1;  
    }  
    return 0;  
}  
  
//遍历  
void Traserval(Stack *S)  
{  
    printf("\n");  
    while(S->next != NULL)   
    {  
        printf("%d\n", S->next->data);  
        S = S->next;  
    }  
}  
  
  
  
  
  
  
  
  
  
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值