头疼的算法与数据结构——链表实现栈

实现栈的功能可以用数组和链表,这里我用链表写了一个栈。

实现主要思想:

(1)因为栈时后进先出的,所以我们在使用链表压栈的时候,将要压栈的那个元素放到头节点。
(2)出栈就是删除头节点,因为你后面插入的节点在头节点。


代码实现:

#include <stdio.h>
#include <stdlib.h>


struct node{
    int data;
    struct node *next;
};
typedef struct node Node;
#define SIZE sizeof(Node)
Node* creteNode(int d);
void push(Node** h);
int addFont(int d,Node** h);
void pop();

//创建节点
Node* creteNode(int d)
{
    Node* pn=(Node*)malloc(SIZE);
    pn->data=d;
    pn->next=NULL;
    return pn;
}

//压栈
void push(Node** h)
{
    Node* pn=NULL;
    Node* p=NULL;
    int d;
    printf("请输入数据\n");
    scanf("%d",&d);
    pn=creteNode(d);
    *h=pn;
    p=*h;
    while(1)
    {
        printf("请输入数据\n");
        scanf("%d",&d);
        if(d==0)
            break;
        addFont(d,h);
    }
}

//头插法
int addFont(int d,Node** h)//修改头节点  传入二级指针
{
    Node* pn=NULL;
    pn=creteNode(d);
    pn->next=*h;
    *h=pn;
}

//出栈
void pop(Node** h)
{
    Node* pd=*h;
    *h=pd->next;
    printf("%d:出栈\n",pd->data);
    free(pd);
    pd=NULL;
}

//打印栈中的元素
void print(Node* h)
{
    printf("list:\n");
    while(h)
    {
        printf("%d ",h->data);
        h=h->next;
    }
    printf("\n");
}

int main()
{
    Node* head=NULL;
    push(&head);
    print(head);
    pop(&head);
    print(head);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值