首页 > 代码库 > 数据结构栈 学习笔记
数据结构栈 学习笔记
栈是先进后出的数据结构。
下面直接上代码了。下面使用数据模仿栈式结构。
// // main.cpp // StudyC++ // // Created by 杜甲 on 14-9-12. // Copyright (c) 2014年 杜甲. All rights reserved. // #include <iostream> //std::cout #include <stdio.h> using namespace std; #define MaxSize 10 int stack[MaxSize]; int top = -1; void push(int value) { int i; if (top >= MaxSize) std::cout<<"\nThe stack is full"<<endl; else { std::cout<<"\nThe stack content before(top->bottom):"<<endl; for (i = top; i >= 0; i--) cout<<stack[i]<<endl; top++; stack[top] = value; //将数据放入数组中 cout<<"The stack content after push(top->bottom):"<<endl; for (i = top; i >= 0; i--) cout<<stack[i]<<endl; } } int pop() { int temp; int i; if (top < 0) { cout<<"The stack is empty!"<<endl; return -1; } cout<<"The stack content before(top->bottom):"<<endl; for (i = top; i >= 0; i--) cout<<stack[i]<<endl; temp = stack[top]; top--; printf("\nThe pop value is [%d]",temp); printf("\nThe stack content after pop(top->bottom):"); for (i = top; i >= 0; i--) printf("[%d]",stack[i]); printf("\n"); return temp; } int main(int argc, const char * argv[]) { //测试 push(3); push(5); push(9); int num = pop(); printf("num = %d\n",num); num = pop(); printf("num = %d\n",num); push(7); return 0; }
用链表模仿栈
// // main.cpp // StudyC++ // // Created by 杜甲 on 14-9-12. // Copyright (c) 2014年 杜甲. All rights reserved. // #include <iostream> //std::cout #include <stdio.h> using namespace std; struct s_node { int data; struct s_node *next; }; typedef struct s_node s_list; typedef s_list *link; link stack = nullptr; void print_stack() { link temp = nullptr; temp = stack; if (temp == nullptr) printf("The stack is empty!\n"); else { while (temp != nullptr) { printf("[%d]",temp->data); temp = temp->next; } printf("\n"); } } void push(int value) { link newnode; printf("\nThe stack content before(top->bottom):"); print_stack(); //初始化 newnode = (link)malloc(sizeof(s_list)); //赋值 newnode->data = http://www.mamicode.com/value;>
原文地址:http://blog.csdn.net/qqmcy/article/details/39393941
数据结构栈 学习笔记
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。