赞 | 0 |
VIP | 133 |
好人卡 | 5 |
积分 | 1 |
经验 | 15036 |
最后登录 | 2017-9-12 |
在线时间 | 190 小时 |
Lv1.梦旅人 彩色的银子
- 梦石
- 0
- 星屑
- 50
- 在线时间
- 190 小时
- 注册时间
- 2006-6-13
- 帖子
- 1361
|
本帖最后由 神思 于 2011-7-18 20:02 编辑
- // TestC.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- #include <stdio.h>
- #include <memory.h>
- typedef struct _tagSTACK_ITEM {
- struct _tagSTACK_ITEM *next;
- int value;
- } STACK_ITEM;
- typedef struct _tagSTACK {
- int length;
- STACK_ITEM *top;
- } STACK;
- short CreateStack(STACK* &ret_stack) {
- STACK* stack = new STACK;
- memset(stack, 0, sizeof(STACK));
- stack->length = 0;
- stack->top = 0;
- ret_stack = stack;
- return 1;
- }
- short CreateStackItem(int value, STACK_ITEM* ret_item) {
- memset(ret_item, 0, sizeof(STACK_ITEM));
- ret_item->value = value;
- ret_item->next = 0;
- return 1;
- }
- void StackPush(STACK *stack, int value) {
- if (stack->top == 0) { /* if stack is empty, let the top of stack goto value. */
- STACK_ITEM* item = new STACK_ITEM;
- memset(item, 0, sizeof(STACK_ITEM));
- CreateStackItem(value, item);
- stack->top = item;
- }
- else { /* if not, insert a new node. */
- STACK_ITEM *item = new STACK_ITEM;
- CreateStackItem(value, item);
- item->next = stack->top;
- stack->top = item;
- }
- stack->length++;
- }
- int StackPop(STACK *stack, int *value) {
- if (stack->length == 0) { /* if stack is null, then it will error. */
- *value = 0;
- return 0;
- }
- /* if not, pop a value. */
- *value = stack->top->value;
- /* move to next */
- STACK_ITEM *stackItem = stack->top;
- stack->top = stack->top->next;
- stack->length--;
- delete stackItem;
- return 1;
- }
- int main() {
- int i = 0;
- int a = 0;
- STACK * stack = 0;
- CreateStack(stack);
- StackPush(stack, 1);
- StackPush(stack, 2);
- StackPush(stack, 3);
- StackPush(stack, 4);
- StackPush(stack, 5);
- for (i = 0; i < 5; i++) {
- if (StackPop(stack, &a)) {
- printf("%d\n", a);
- }
- else {
- printf("\aError! stack is empty! ");
- return -1;
- }
-
- }
-
- return 0;
- }
复制代码 输出
5
4
3
2
1 |
|