公司网站有哪些,wordpress优化主题,广东省住房和城乡建设厅,代发qq群发广告推广C语言 数据结构学习 汇总入口#xff1a; C语言数据结构学习#xff1a;[汇总] 1. 栈
栈#xff0c;实际上是一种特殊的线性表。这里使用的是链表栈#xff0c;链表栈的博客#xff1a;C语言数据结构学习#xff1a;单链表
2. 栈的特点
只能在一端进行存取操作#x… C语言 数据结构学习 汇总入口 C语言数据结构学习[汇总] 1. 栈
栈实际上是一种特殊的线性表。这里使用的是链表栈链表栈的博客C语言数据结构学习单链表
2. 栈的特点
只能在一端进行存取操作导致存取的元素元素有先进后出的特点栈是一种只能在一端进行插入和删除操作的特殊线性表。后进先出Last In First OutLIFO 就像往一个桶里放东西再取东西一样后放进去的东西会先被取出来。基本操作 入栈push将一个元素压入栈顶。例如往栈里放一本书这本书就成为了新的栈顶元素。出栈pop从栈顶取出一个元素。相当于从桌子上拿走最上面的那本书。读栈顶元素peek只查看栈顶元素的值而不取出它。如同看一下最上面那本书是什么但不拿走它。
3. 代码示例 定义新的类型Node用于创建节点 /* 定义新的类型Node用于创建节点 */
typedef struct Node {int data;struct Node* next;
}Node;初始化栈 /* 初始化栈 */
Node* initStack() {Node* S (Node*)malloc(sizeof(Node));S-data 0;S-next NULL;return S;
}入栈push、出栈pop、读栈顶元素peek /* 出栈 */
//判断栈是否为空
int isEmpty(Node* S) {if (S-data 0 || S-next NULL) {return 1;}else{return 0;}
}
//出栈
int pop(Node* S) {if (isEmpty(S)) {return -1;}else {Node* current S-next; //获取第一个元素int data current-data; //获取第一个元素的dataS-next current-next; //把栈头的next指向当前的nextfree(current); //释放当前return data; //返回data}
}/* 入栈 */
void push(Node* S, int data) {Node* node (Node*)malloc(sizeof(Node));node-data data;node-next S-next;S-next node;S-data;
}/* 读栈顶元素 */
int peek(Node* S) {if (isEmpty(S)) {return -1;}else {S-data--;return S-next-data;}
}打印栈 /* 打印栈 */
void printStack(Node* S) {Node* current S-next;while (current){ //当前不为空则进入printf(%d , current-data);current current-next;}printf(NULL\\n);
}测试 /* 测试 */
int main(void)
{Node* S initStack();push(S, 1);printStack(S);push(S, 2);printStack(S);push(S, 3);printStack(S);push(S, 4);printStack(S);push(S, 5);printStack(S);pop(S);printStack(S);pop(S);printStack(S);pop(S);printStack(S);pop(S);printStack(S);return 0;
}