Stack栈
栈,用处很多,程序的中断等;FILO或LIFO,first in last out,last in first out
栈,有两种实现方法,一个是通过数组Array,另一个是通过链表Linked list。
通过Array
优点
- 很容易实现,节省空间相对于链表,因为链表需要指针。
缺点
- 由于数组是静态存储的,不能Grow和Shrink。
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 //represent stack by array 5 struct stack 6 { 7 int top; 8 unsigned capacity; 9 int * array; 10 }; 11 struct stack * creatStack(unsigned capacity) 12 { 13 struct stack * new_stack = (struct stack *)malloc(sizeof(struct stack)); 14 new_stack->top = -1; 15 new_stack->capacity = capacity; 16 new_stack->array = (int *)malloc(new_stack->capacity * sizeof(int)); 17 printf("\nCreat is OK!\n"); 18 return new_stack; 19 } 20 int isFull(struct stack * s) 21 { 22 return s->top == (s->capacity-1); 23 } 24 int isEmpty(struct stack *s) 25 { 26 return s->top == -1; 27 } 28 void push(struct stack * s, int data) 29 { 30 if(isFull(s)) 31 { 32 printf("\nThe stack is full"); 33 return ; 34 } 35 //假如capacity为10 36 // -1 0 1 2 3 4 5 6 7 8 37 // 0 1 2 3 4 5 6 7 8 9 38 s->array[++(s->top)] = data; 39 printf("\n The %2d pushed to stack", data); 40 } 41 int pop(struct stack * s) 42 { 43 if(isEmpty(s)) 44 { 45 printf("\nThe stack is empty"); 46 return ; 47 } 48 return s->array[(s->top)--]; 49 } 50 int main(void) 51 { 52 struct stack * love = creatStack(10); 53 push(love, 1); 54 push(love, 2); 55 push(love, 3); 56 push(love, 4); 57 push(love, 5); 58 push(love, 6); 59 push(love, 7); 60 push(love, 8); 61 push(love, 9); 62 push(love, 10); 63 64 int num = pop(love); 65 printf("\nNow the Stack top is %d", love->array[love->top]); 66 return 0; 67 }
通过Linked list实现
优点
- 链表存储时动态的,可以Grow和Shrink
缺点
- 指针耗费空间资源
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<limits.h> 4 5 //Represent Stack on linked list. 6 struct Stack 7 { 8 int data; 9 struct Stack * next; 10 }; 11 struct Stack * newNode(int data) 12 { 13 struct Stack * newNode = (struct Stack *)malloc(sizeof(struct Stack)); 14 15 newNode->data = data; 16 newNode->next = NULL; 17 18 return newNode; 19 } 20 int isEmpty(struct Stack * root) 21 { 22 return NULL == root; 23 } 24 void push(struct Stack ** root, int data) 25 { 26 struct Stack * new_node = newNode(data); 27 new_node->next = (*root); 28 (*root) = new_node; 29 30 printf("\n%d pushed to Stack", data); 31 } 32 int pop(struct Stack ** root) 33 { 34 if(isEmpty((*root))) 35 { 36 printf("The stack is empty"); 37 return -1; 38 } 39 struct Stack * node = (*root); 40 int number = node->data; 41 (*root) = node->next; 42 43 free(node); 44 return number; 45 } 46 int peek(struct Stack * root) 47 { 48 if(isEmpty(root)) 49 { 50 return INT_MIN; 51 } 52 53 return root->data; 54 } 55 int main(void) 56 { 57 struct Stack * top = NULL; 58 push(&top, 1); 59 push(&top, 2); 60 push(&top, 3); 61 push(&top, 4); 62 push(&top, 5); 63 push(&top, 6); 64 65 printf("\n%d get out of the stack", pop(&top)); 66 printf("\nThe stack`s top is %d", peek(top)); 67 return 0; 68 }
人生如茶需慢品