c++ 采用链式结构实现关于入栈,出栈,打印栈的操作

3/8/2017来源:ASP.NET技巧人气:381

c++标准的库模板中,有专门的容器栈,但是为了巩固下对栈的理解,用结构体以链式结构写了个小demo,留着备用 #include #include"stdafx.h" using namespace std; struct node { int data; node* next; };//栈元素 struct  stack_top { node  * top; int cout; };//栈顶元素,定义的一个游标 void push_stack(stack_top *p, node *new_node) { new_node->next = p->top; p->top = new_node; p->cout++; }//入栈,下标为n的节点的next指向下标为n-1的节点,top始终指向头节点 void PRint_node(stack_top * p) { node * temp; temp= new node; temp= p->top; for (int i = 0; i < p->cout; i++) { cout << temp->data<< "   "; temp = temp->next;//为了不破坏游标即top和头节点的链接性 } } void pop_stack(stack_top *p) { node * e; e = p->top; p->top = p->top->next; free(e); p->cout--; }//后入先出 void main() { node * stack; stack = new node; stack_top * top1; top1 = new stack_top; top1->top = stack; top1->cout = 0; node * new_node; for (int i=0; i < 10; i++) { new_node = new node; new_node->data = i; push_stack(top1, new_node); } print_node(top1); cout << endl; pop_stack(top1); print_node(top1); }