链式栈的实现(头文件及源程序)
生活随笔
收集整理的這篇文章主要介紹了
链式栈的实现(头文件及源程序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
鏈式棧的實現(頭文件及源程序)
Linkedstack.h
#ifndef __LINKEDSTACK_H__ #define __LINKEDSTACK_H__//元素類型定義 typedef int ElemType_stack;//結點結構體類型定義 typedef struct Node_stack {ElemType_stack data;struct Node_stack *next;struct Node_stack *front;}Node_stack;//棧類型定義 typedef struct Linkedstack {int num;Node_stack *top; //棧頂指針Node_stack *bottom; //棧底指針 }Linkedstack;//創建一個空棧 Linkedstack *Init_stack();//創建一個新結點 Node_stack *Create_New_Node_stack(ElemType_stack value);//入棧 void push_stack(Linkedstack *linkedstack, ElemType_stack value);//出棧 void pop_stack(Linkedstack *linkedstack);//銷毀一個棧 void destroy_stack(Linkedstack *linkedstack);//讀取棧頂元素 ElemType_stack get_stack_top(Linkedstack *linkedstack);//判斷棧空 int empty_stack(Linkedstack *linkedstack);//獲取棧的元素個數 int length_stack(Linkedstack *linkedstack);#endifLinkedstack.c
#include <stdio.h> #include <stdlib.h> #include "linkedstack.h"//棧初始化 Linkedstack *Init_stack( ) {Linkedstack *linkedstack = malloc(sizeof(Linkedstack));linkedstack->num = 0;linkedstack->top = NULL;linkedstack->bottom = NULL;return linkedstack; }//創建一個新結點 Node_stack *Create_New_Node_stack(ElemType_stack value) {Node_stack *new_node = malloc(sizeof(Node_stack));new_node->data = value;new_node->next = NULL;new_node->front = NULL;return new_node; }//入棧 void push_stack(Linkedstack *linkedstack, ElemType_stack value) {if (linkedstack == NULL){printf("棧不存在!\n");return;}Node_stack *new_node = Create_New_Node_stack(value);if (linkedstack->num == 0){linkedstack->top = new_node;linkedstack->bottom = new_node;new_node->front = linkedstack->top;}else{linkedstack->top->next = new_node;new_node->front = linkedstack->top;linkedstack->top = new_node;}linkedstack->num++; }//出棧 void pop_stack(Linkedstack *linkedstack) {if (linkedstack == NULL){printf("棧不存在!\n");return;}if (linkedstack->num == 1){linkedstack->top->front = NULL;free(linkedstack->top);linkedstack->top = NULL;linkedstack->bottom = NULL;}else{linkedstack->top = linkedstack->top->front;free(linkedstack->top->next);linkedstack->top->next = NULL;}linkedstack->num--;}//銷毀一個棧 void destroy_stack(Linkedstack *linkedstack) {if (linkedstack == NULL){printf("棧不存在!\n");return;}else{while (linkedstack->num != 0){pop_stack(linkedstack);}//free(linkedstack);linkedstack = NULL;} }//讀取棧頂元素 ElemType_stack get_stack_top(Linkedstack *linkedstack) {if (linkedstack == NULL){printf("棧不存在!\n");return 0;}if (linkedstack->num == 0){printf("棧已空,獲取棧頂元素失敗!");return 000;}else{return linkedstack->top->data;} }//判斷棧空 int empty_stack(Linkedstack *linkedstack) {if (linkedstack == NULL){printf("棧不存在!\n");return -1;}if (linkedstack->num == 0){return 1; //棧空}else{return 0; //棧非空} }//獲取棧的元素個數 int length_stack(Linkedstack *linkedstack) {if (linkedstack == NULL){printf("鏈表不存在!\n");return 0;}return linkedstack->num; }總結
以上是生活随笔為你收集整理的链式栈的实现(头文件及源程序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 非常有用的高级函数PATH_SE
- 下一篇: 获取Class对象方式