5-31 2,504 views
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
#include <stdio.h> #include <stdlib.h> struct TNode { int number; TNode* lchild; TNode* rchild; }; struct Stack { TNode** top; TNode** base; int size; }; void Init(Stack* s) { s->size = 100; s->base = (TNode**)malloc(sizeof(TNode*)*s->size); s->top = s->base; } void Push(Stack* s,TNode* n) { if(s->top-s->base>=s->size) { s->size = s->size+10; s->base = (TNode**)realloc(s->base,sizeof(TNode*)*s->size); } *s->top = n; s->top = s->top+1; } void Pop(Stack* s,TNode* &n) { if(s->top-s->base<=0) return; s->top = s->top-1; n = *s->top; } int Empty(Stack* s) { if (s->top-s->base<=0) return 1; else return 0; } int main() { Stack *s; s = (Stack*)malloc(sizeof(Stack)); Init(s); TNode* tree; tree = (TNode*)malloc(sizeof(TNode)); tree->number = 1; tree->lchild = (TNode*)malloc(sizeof(TNode)); tree->lchild->number = 2; tree->lchild->lchild = NULL; tree->lchild->rchild = NULL; tree->rchild = (TNode*)malloc(sizeof(TNode)); tree->rchild->number = 3; tree->rchild->lchild = (TNode*)malloc(sizeof(TNode)); tree->rchild->lchild->number = 4; tree->rchild->lchild->lchild = NULL; tree->rchild->lchild->rchild = NULL; tree->rchild->rchild = (TNode*)malloc(sizeof(TNode)); tree->rchild->rchild->number = 5; tree->rchild->rchild->lchild = NULL; tree->rchild->rchild->rchild = NULL; TNode* node; node = tree; while(node) { printf("%d ",node->number); Push(s,node); node = node->lchild; } while(Empty(s)!=1) { Pop(s,node); node = node->rchild; while(node) { printf("%d ",node->number); Push(s,node); node = node->lchild; } } return 0; } |