今天給大家介紹棧的鏈式結構,用dev-c++4.9.9.2調試通過,少廢話直接上代碼:
數據結構體存放文件stacklist.h文件如下
#ifndef _STACKLIST_H_ #define _STACKLIST_H_ typedef struct _Node { int data; struct _Node *pre; struct _Node *next; }Node,*pNode; typedef struct _Stack_Header { struct _Node *botton; struct _Node *top; int size; }Stack_Header,*pStack_Header; pStack_Header init_stack_list(void); pNode push_node(pStack_Header plist,int data); pNode pop_node(pStack_Header plist); int print_stack_list(pStack_Header plist); #endif
函數存放文件stacklist.c
/******************************* 時間:2014.12.12 作者:XIAO_PING_PING 內容:棧的鏈式數據結構 功能:學習些數據結構 ********************************/ #include#include #include #include "stacklist.h" /*初始化一個堆棧鏈表*/ pStack_Header init_stack_list(void) { pStack_Header plist; pNode p; plist = (Stack_Header *)malloc(sizeof(Stack_Header)); plist->botton = NULL; plist->top = NULL; plist->size = 0; return plist; } /*往堆棧裡面添加節點,數據data*/ pNode push_node(pStack_Header plist,int data) { pNode p; p = (Node *)malloc(sizeof(Node)); p->data = data; p->next = NULL; p->pre = plist->top; if((plist->top == NULL) && (plist->botton == NULL)) { plist->top = p; plist->botton = p; plist->size = 1; printf("入棧第1個節點\n"); return p; } plist->top->next = p; plist->top = p; plist->size += 1; printf("入棧第%d個節點\n",plist->size); return plist->top; } /*出棧刪除節點*/ pNode pop_node(pStack_Header plist) { pNode p; if(0 == plist->size) { printf("棧區沒有節點,無法完成出棧\n"); return plist->top; } p = plist->top; plist->top = plist->top->pre; if(NULL != plist->top) { plist->top->next = NULL; } else { plist->botton = NULL; } free(p); plist->size -= 1; printf("出棧第%d個節點\n",plist->size + 1); return plist->top; } /*打印入棧數據*/ int print_stack_list(pStack_Header plist) { pNode p; if((plist->top == plist->botton) && (0 == plist->size)) { printf("棧區沒有節點\n"); return -1; } p = plist->botton; printf("從棧底開始打印數據\n"); while(plist->top != p) { printf("%d ",p->data) ; p = p->next; } printf("%d ",p->data) ; printf("\n打印完畢\n"); return 0; }
測試文件test.c
#include#include #include #include "stacklist.h" int main() { pStack_Header plist; plist = init_stack_list(); push_node(plist,13); push_node(plist,1); push_node(plist,232); push_node(plist,143); print_stack_list(plist); pop_node(plist); pop_node(plist); pop_node(plist); //pop_node(plist); //pop_node(plist); printf("\n"); print_stack_list(plist); getch(); }
運行結果如下圖: