数据结构示例之用链表实现栈

来源:互联网 发布:淘宝香水嗅觉系真假 编辑:程序博客网 时间:2024/06/01 08:59

以下是“使用链表实现栈”的简单示例:

1. 用c语言实现的版本

#include<stdio.h>#include<stdlib.h>struct s_node{int data;struct s_node *next;};typedef struct s_node* pNode;pNode stack = NULL;int pCount = 0;/* 打印栈的内容 */void print_stack(){pNode temp = NULL;temp = stack;if (temp == NULL){printf("The stack is empty!\n");}else{while (temp != NULL){printf("[%d]", temp->data);temp = temp->next;}printf("\n");}}/* 入栈,从头部插入 */void push(int value){if (stack){pNode newnode;newnode = (pNode)malloc(sizeof(s_node)); if (!newnode){printf("malloc fail, please check!");return;}newnode->data = value;newnode->next = stack;stack = newnode;++pCount;}else{stack = (pNode)malloc(sizeof(s_node));if (!stack){printf("malloc fail, please check!");return;}stack->data = value;stack->next = NULL;++pCount;}}/* 出栈,从头部删除 */void pop(int *value){pNode top;if (stack != NULL){top = stack;stack = stack->next;*value = top->data;free(top);--pCount;}else{pCount = 0;}}void main(){pNode point;int select;int value;printf("(1)Input a stack data.\n");printf("(2)Output a stack data.\n");printf("(3)Exit\n");printf("Please select your choice: ");scanf("%d", &select);do{switch (select){case 1:printf("Before push, the stack content (top->bottom) is: \n");print_stack(); /* 打印栈的内容 */printf("Please input the digit: ");scanf("%d", &value);push(value);printf("After push, the stack content (top->bottom) is: \n");print_stack();break;case 2:printf("Before pop, the stack content (top->bottom) is: \n");print_stack(); /* 打印栈的内容 */if (pCount) {pop(&value);printf("The output value is: [%d].\n", value);printf("After pop, the stack content (top->bottom) is: \n");print_stack();}else{printf("The stack is empty, it can not be poped!");}break;default:printf("Please input the right choice!");break;}printf("\n(1)Input a stack data.");printf("\n(2)Output a stack data.");printf("\n(3)Exit.");printf("\nPlease select your choice: ");scanf("%d", &select);} while (select != 3);}

运行结果如下所示:



0 0
原创粉丝点击