线性表之链表实现栈结构

本文介绍如何使用单链表实现栈的数据结构,并提供具体的代码实现。栈是一种后进先出(LIFO)的数据结构,仅允许在一端进行插入和删除操作。

用链表实现栈结构

栈结构简单介绍

栈结构通俗来说是元素先进后出,就像一个水瓶,依次往里装东西,最先装进去的被压在下面,要出来时得先拿走上面压着的东西,  
才能取出来。所以说栈是运算受限的线性表,因为栈只允许在表的一端进行增删。

实现

 本文使用单链表来实现栈结构。先构建一个带head 节点的链表,每次添加元素(进栈),  
 使新节点->next指向head->next,使head节点指向新节点。数组结构的实现见下一篇。

具体实现代码如下


//定义节点
typedef struct data{
    int value;
    struct data *next;

}node;

//初始化node
node *newData(int age){

    //动态分配内存
    node *p = (node *)malloc(sizeof(node));
    p->value = age;
    return p;
}

//建立空栈
node *newStack(){

    //建立头结点
    node *head = newData(-1);

    //头结点的下一个节点置空
    head->next = NULL;

    return head;
}

//add element in first 进栈
void pash(node *head, node *p){
    //将元素添加到表头,以实现栈结构

    p->next = head->next;

    head->next = p;

}


//出栈
void pop(node *head){
    if(isEmpty(head)){
        printf("the stack is empty");
        exit(1);
    }
    node *p = head->next;

    head->next = head->next->next;

    free(p);
}

//取栈顶
node *getTop(node *head){
    if(isEmpty(head)){
            return NULL;
    }
    return head->next;

}

//判栈空
int isEmpty(node *head){
    if(head->next == NULL){
        return 1;
    }
    return 0;
}

void test(){
    node *head = newStack();
    pash(head,newData(1));
    pash(head,newData(2));
    pash(head,newData(3));
    pash(head,newData(4));
    pash(head,newData(5));

    while(!isEmpty(head)){
        printf("%d\n",getTop(head)->value);
        pop(head);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值