单向链表实现栈

/*
 * Do:单向链表实现栈
 * By:LJDong
 * Time:2018.9.19
 * 
*/
#include <stdio.h>
#include <malloc.h>
 
//单向链表的“节点”
struct node
{
    int val;
    struct  node* next;
};
//单向链表的“表头”
static struct node *phead=NULL;
//创建节点,val为节点值
static struct node* createNode(int val)
{
    struct node *pnode=NULL;
    pnode=(struct node*)malloc(sizeof(struct node));
    if(!pnode)
    {
        return NULL;
        printf("Create Node Error !");
    }
    pnode->val = val;
    pnode->next=NULL;
    return pnode;
 
}
//销毁单项链表
static int destroyList()
{
    struct node *pnode = NULL;
    while(phead!=NULL)
    {
        pnode=phead;
        phead=phead->next;
        free(pnode);
    }
    return 0;
 
}
//将val插入到链表的表头位置
static struct node* push(int val)
{
    struct node *pnode=NULL;
 
    pnode=createNode(val);
    pnode->next = phead;
    phead=pnode;
    return phead;
}
//删除链表的表头
static int pop()
{
    if(!phead)
    {
        printf("List is Empty !");
        return -1;
    }
    int ret;
    struct node *pnode;
    ret=phead->val;
    pnode=phead;    
    phead=phead->next;
    free(pnode);
    return ret;
 
}
//返回链表中表头节点的值
static int peek()
{
    if(!phead)
    {
        printf("peek failed! , Link is Empty !");
        return -1;
    }
    return phead->val;
}
//返回链表中节点的个数
static int size()
{
    int count;
    count=0;
    struct node *pnode=phead;
    while(pnode!=NULL)
    {
        pnode=pnode->next;
        count++;
    }
    return count;
}
//链表是否为空
static int isEmpty()
{
    return phead==NULL;
}
//打印栈
static void printStatck()
{
    if(isEmpty()==0)
    {
        printf("Stack is Empty !");
    }
    printf("size = %d\n" ,size());
    struct node *pnode=NULL;
    while(phead!=NULL)
    {
        printf("%d\n",phead->val);
        pnode=phead;
        phead=phead->next;
        free(pnode);
    }
}
 
int main()
{
    int temp;
    //将10,20,30依次推入栈中
    push(10);
    push(20);
    push(30);
    //打印栈
    printStatck();
    //将栈顶元素赋值给temp,并删除栈顶元素
    temp=peek();
    printf("temp = %d\n",temp);
    //打印栈
    printStatck();
    push(40);
    //打印栈
    printStatck();
    //销毁栈
    destroyList();
 
}

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值