编程实现栈的入栈与出栈操作
2013-09-06 21:22
204 查看
#include <tchar.h> #include <iostream> using namespace std; typedef struct student{ int data; struct student * next; } node; typedef struct linkmyqueue{ node *below; node *top; } myqueue; node* create() { node *head, *p, *s; int x, cycle = 1; head = (node *)malloc(sizeof(node)); p = head; while(cycle) { cout << "please input the data: "; cin >> x; cout << endl; if( x != 0) { s = (node *)malloc(sizeof(node)); s->data = x; p->next = s; p = s; } else { cycle = 0; } } p->next = NULL; head = head->next; return head; } int length(node *head) { int n = 0; node *p; p = head; while (p != NULL) { p = p->next; n++; } return n; } void print(node *head) { int n; node *p; p = head; n = length(head); cout << "There is " << n << " data in list\n" << endl; while(p != NULL) { cout << p->data << " -> "; p = p->next; } cout << endl; } node *last(node *head) { node *p; p = head; while(p->next != NULL) p = p->next; return p; } myqueue *push(myqueue *LQ, int x) { node *p; p = (node *)malloc(sizeof(node)); p->data = x; p->next = NULL; if(LQ->below == NULL) { LQ->below = p; LQ->top = p; } else { LQ->top->next = p; LQ->top = p; } return LQ; } myqueue *pop(myqueue * LQ) { node *p, *q; if(LQ->below == NULL) { cout<<"the queue is overflow!"<<endl; return LQ; } p = LQ->below; if(LQ->below == LQ->top) { LQ->below = NULL; LQ->top = NULL; free(p); } else { q = LQ->top; while(p->next != LQ->top) { p = p->next; } LQ->top = p; LQ->top->next = NULL; free(q); } return LQ; } int _tmain(int argc, _TCHAR * argv[]) { node *head, *end; myqueue *LQ; head = create(); end = last(head);//获取尾节点指针 print(head); LQ = (myqueue *)malloc(sizeof(myqueue));//给栈分配内存空间 LQ->below = head; LQ->top = end; for (int i=1; i<=4; i++) { LQ = push(LQ, i); } print(head); for (i=1; i<=2; i++) { LQ = pop(LQ); } print(LQ->below); return 0; }
相关文章推荐
- 采用顺序存储实现栈的初始化、入栈、出栈操作。
- 顺序栈的定义、初始化、出栈、入栈等操作 C++代码实现 ——感想
- Java 用数组实现栈 (Stack),包括栈的初始化,入栈、出栈等操作
- 2.1.1线性表实现栈的建立,入栈,出栈等操作
- 顺序栈的定义、初始化、出栈、入栈等操作 C++代码实现
- 数据结构栈的数组实现初始化,入栈,出栈,获取栈顶元素,栈的长度等操作
- 剑指offer 21---实现一个栈, 要求实现Push( 出栈) 、 Pop( 入栈) 、 Min( 返回最小值的操作) 的时间复杂度为O(1)
- 实现一个出栈,入栈,返回最小值的操作的时间复杂度为O(1)的栈
- 编程实现一个栈结构,用数组来实现,具有入栈、出栈操作。
- c++ 采用链式结构实现关于入栈,出栈,打印栈的操作
- C语言实现顺序栈的基本操作(初始化、判断空、入栈、出栈、获取栈顶元素)
- 采用链式存储实现,进栈、出栈操作
- C#编程技巧 轻松实现对文件的操作
- 周志华《机器学习》课后习题解答系列(五):Ch4.4 - 编程实现CART算法与剪枝操作
- [VC网络编程笔记-使用API函数操作互斥对象实现线程同步
- VS2010 C++ 操作Excel表格的编程实现
- 笔试面试常考数据结构-单链表常用操作编程实现
- 【栈队列】实现一个栈Stack,要求实现Push(出栈)、Pop(入栈)、Min(返回最小值的操作)的时间复杂度为O(1)
- 实现一个栈,要求实现Push(出栈)、Pop(入栈)、Min(返回最小值的操作)的时间复杂度为O(1)
- 编写程序,实现顺序栈的创建、进栈和出栈等基本操作算法。