头疼的算法与数据结构——链表实现栈
来源:互联网 发布:五羊宝宝洗衣液 知乎 编辑:程序博客网 时间:2024/06/07 21:45
实现栈的功能可以用数组和链表,这里我用链表写了一个栈。
实现主要思想:
(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;}
1 0
- 头疼的算法与数据结构——链表实现栈
- 头疼的算法与数据结构——循环链表详解
- 头疼的算法与数据结构——双向循环链表
- 头疼的算法与数据结构——单链表详解
- 头疼的算法与数据结构——红黑树
- 头疼的算法与数据结构——约瑟夫环
- 头疼的算法与数据结构——详解选择排序法
- 头疼的算法与数据结构——详解插入排序法
- 头疼的算法与数据结构——二维数组中的查找
- 头疼的算法与数据结构——八皇后问题(递归法)
- 头疼的算法与数据机构——判断链表是否有环
- 《数据结构与算法分析》—栈的链表和数组实现(C语言)
- [数据结构与算法分析] 栈的链表实现
- 数据结构与算法学习之路:简单的电话簿实现——单向链表
- 数据结构与算法分析-栈的实现
- Java数据结构与算法---栈的实现
- 数据结构与算法分析-单向链表的实现
- 数据结构与算法分析-双向链表的实现
- centos7中安装elasticsearch5.2
- getParameter和getAttribute的区别
- mui.css实现选项卡功能
- 计算机基础之Http协议1
- webmagic是个神奇的爬虫(二)-- webmagic爬取流程细讲
- 头疼的算法与数据结构——链表实现栈
- spring security 配置类方式实现(1)
- Android复制asset目录的文件到SD卡下
- CentOS6.8x64二进制方式安装MYSQL5.7
- windows下获得一个指定文件路径下的所有文件
- 简单聊聊TestNG中的并发
- 166. Fraction to Recurring Decimal Medium
- hdu 1157
- Allow only specific IPs access in tomcat