1. 程式人生 > >數據結構--實驗1--棧的操作

數據結構--實驗1--棧的操作

har 菜單 max can 十進制 malloc get char 建立

  1 #include "stdio.h"
  2 #include "malloc.h"
  3 typedef  int datatype;
  4 typedef  struct node   //定義鏈式棧結構
  5 {    datatype data;
  6     struct node *next;
  7 }StackNode,*LinkStack;
  8 LinkStack  Init_LinkStack()
  9 {  
 10     return NULL;
 11 }
 12 
 13 //入棧   
 14 LinkStack  Push_LinkStack(LinkStack  top, datatype x)         
15 { 16 StackNode *s; 17 s=new StackNode; 18 s->data=x; 19 s->next=top; 20 top=s; 21 return top; 22 } 23 24 //出棧 25 LinkStack Pop_LinkStack (LinkStack top, datatype *x) 26 { 27 StackNode *p; 28 if(top==NULL)return NULL;
29 else 30 { 31 *x=top->data; 32 p=top; 33 top=top->next; 34 free(p); 35 return top; 36 } 37 38 } 39 void print(LinkStack top) 40 { StackNode *p=top; 41 while(p != NULL) 42 { 43 printf("%d->",p->data); 44 p=p->next;
45 } 46 } 47 //順序棧 48 #define MAXSIZE 1024 49 typedef struct 50 { datatype data[MAXSIZE]; 51 int top; 52 }SeqStack; 53 54 //順序棧置空棧:首先建立棧空間,然後初始化棧頂指針。 55 SeqStack *Init_SeqStack() 56 { SeqStack *s; 57 s=new SeqStack; 58 s->top= -1; 59 return s; 60 } 61 62 //順序棧判空棧 63 int Empty_SeqStack(SeqStack *s) 64 { if (s->top == -1) return 1; 65 else return 0; 66 } 67 68 //順序棧入棧 69 int Push_SeqStack (SeqStack *s, datatype x) 70 {if (s->top == MAXSIZE-1) return 0; //棧滿不能入棧 71 else { s->top++; 72 s->data[s->top]=x; 73 return 1; 74 } 75 } 76 77 //順序棧出棧 78 int Pop_SeqStack(SeqStack *s, datatype *x) 79 { 80 if (Empty_SeqStack(s)) return 0; //棧空不能出棧 81 else { *x=s->data[s->top]; 82 s->top--; return 1; //棧頂元素存入*x,返回 83 } 84 } 85 void conversion(int N,int r) 86 { SeqStack *s; 87 datatype x; 88 s=Init_SeqStack(); //初始化棧 89 printf("\n %d 的十進制數轉換成 %d 進制為: ",N,r); 90 while ( N ) 91 { Push_SeqStack (s,N%r); //余數入棧 92 N=N/r ; //商作為被除數繼續 93 } 94 while ( !Empty_SeqStack(s)) 95 { Pop_SeqStack (s,&x) ; 96 printf(" %d ",x) ; 97 } 98 } 99 void main() 100 { 101 datatype x; 102 int i,j,k; 103 LinkStack top; 104 top=Init_LinkStack(); 105 do 106 { 107 printf("\n\n\n\n"); 108 printf("\t\t\t 棧的應用子系統\n"); 109 printf("\t\t*******************************\n"); 110 printf("\t\t* 1----鏈式進棧    *\n"); 111 printf("\t\t* 2----鏈式出棧    *\n"); 112 printf("\t\t* 3----鏈棧顯示    *\n"); 113 printf("\t\t* 4----進制轉換    *\n"); 114 printf("\t\t* 0----返  回    *\n"); 115 printf("\t\t*******************************\n"); 116 printf("\t\t 請選擇菜單項(0-4):"); 117 scanf("%d",&k); 118 getchar(); 119 switch(k) 120 { 121 case 1: 122 printf("\n 請輸入要進棧的數據X:"); 123 scanf("%d",&x); 124 top=Push_LinkStack(top,x); 125 break; 126 case 2: 127 Pop_LinkStack(top,&x); 128 break; 129 case 3: 130 printf("\n 鏈式棧的元素有:"); 131 print(top); 132 break; 133 case 4: 134 int N,r; 135 printf("\n 請輸入一個整數N="); 136 scanf("%d",&N); 137 printf("\n 請輸入一個要轉換的進制數r="); 138 scanf("%d",&r); 139 conversion(N,r); 140 break; 141 142 } 143 144 }while(k); 145 }

數據結構--實驗1--棧的操作