棧,遞歸
阿新 • • 發佈:2017-11-22
ron 判斷 type strong 連接 temp es2017 基本操作 16px
- 棧的基本操作
註意:是從後往前連接的
1 #include <stdio.h> 2 #include <Windows.h> 3 typedef struct sStack 4 { 5 int num; 6 struct sStack* pnext; 7 }Stack; 8 void push(Stack **pStack,int num); 9 int pop(Stack **pStack); 10 BOOL isEmpty(Stack *pStack); 11 12 int main() 13 { 14 Stack* pStack = NULL;15 push(&pStack,1); 16 push(&pStack,2); 17 push(&pStack,3); 18 printf("%d\n",pop(&pStack)); 19 printf("%d\n",pop(&pStack)); 20 printf("%d\n",pop(&pStack)); 21 printf("%d\n",pop(&pStack)); 22 if( isEmpty(pStack)) 23 printf("棧為空\n"); 24 return 0; 25 } 26 void push(Stack **pStack,int num) 27 { 28 Stack* stack = (Stack*)malloc(sizeof(Stack)); 29 stack->num = num; 30 stack->pnext = NULL; 31 32 stack->pnext = *pStack; 33 *pStack = stack; 34 //不需要判斷棧是否為空,直接push就好 35 } 36 int pop(Stack **pStack)37 { 38 int a = 0; 39 Stack* temp; 40 if(isEmpty( *pStack)) 41 return -1; 42 a = (*pStack)->num; 43 temp = *pStack; 44 (*pStack) = (*pStack)->pnext; 45 free(temp);//彈出之後要刪除 46 return a; 47 } 48 BOOL isEmpty(Stack *pStack) 49 { 50 if(pStack == NULL) 51 return TRUE; 52 else 53 return FALSE; 54 }基本操作
- 遞歸
1 #include <stdio.h> 2 int JIECHENG(int); 3 void Out(int,int ); 4 int main() 5 { 6 printf("%d\n",JIECHENG(5)); 7 Out(1,4); 8 return 0; 9 } 10 int JIECHENG(int num) 11 { 12 if(num == 1) 13 { 14 return 1; 15 } 16 else return num*JIECHENG(num-1); 17 } 18 void Out(int begin,int end) 19 { 20 if(begin <= end) 21 { 22 printf("%d\n",begin); 23 Out(begin+1,end); 24 printf("%d\n",begin); 25 } 26 }
棧,遞歸