栈是先进后出的数据结构。
下面直接上代码了。下面使用数据模仿栈式结构。
// // 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 = value; //栈是先进后出 将之前的节点放到后面 newnode->next = stack; //将新的放到前面 stack = newnode; } int pop() { link top; int temp; printf("\nThe stack content before(top->bottom):"); print_stack(); if (stack != nullptr) { top = stack; stack = stack->next; temp = top->data; free(top); return temp; }else{ return -1; } } int main(int argc, const char * argv[]) { push(9); push(10); pop(); push(11); print_stack(); return 0; }
原文地址:http://blog.csdn.net/qqmcy/article/details/39393941
时间: 2024-11-10 15:17:02