1. 程式人生 > >Stack棧——getMin()

Stack棧——getMin()

void std stack ack spa next printf other pty

獲取棧——stack中最小的元素

  1. 建立另一個棧——temp
  2. 如果兩個棧都為空,則將node同時push兩個棧中
  3. 接著插入new_node,如果temp不為空,則比較棧頂node->data和new_node->data。
  4. 如果node->data大於new_node->data,則將new_node同時push兩個棧中
  5. 反之,只push進stack棧中
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 struct stack
 5 {
 6     int data;
 7     struct
stack * next; 8 }; 9 struct stack * newNode(int data) 10 { 11 struct stack * new_node = (struct stack *)malloc(sizeof(struct stack)); 12 new_node->data = data; 13 new_node->next = NULL; 14 } 15 void push(struct stack ** root, int data) 16 { 17 struct stack * new_node = newNode(data);
18 19 new_node->next = (*root); 20 (*root) = new_node; 21 printf("\n%-2d pushed to stack", data); 22 } 23 int isEmpty(struct stack * root) 24 { 25 return NULL == root ? 1 : 0; 26 } 27 int pop(struct stack ** root) 28 { 29 if(isEmpty((*root))) 30 { 31 printf("\nEmpty!
"); 32 return 0; 33 } 34 struct stack * temp = (*root); 35 int num = temp->data; 36 (*root) = temp->next; 37 free(temp); 38 39 return num; 40 } 41 void push_new(struct stack ** root, struct stack ** other, int data) 42 { 43 if(NULL == (*root) || NULL == (*other)) 44 { 45 push(root, data); 46 push(other, data); 47 } 48 else if(data < ((*other)->data)) 49 { 50 printf("\n%-2d poped off", pop(other)); 51 push(other, data); 52 push(root, data); 53 }else if(data > ((*other)->data)) 54 { 55 push(root, data); 56 } 57 } 58 int getMin(struct stack * other) 59 { 60 return other->data; 61 } 62 int main(void) 63 { 64 struct stack * root = NULL; 65 struct stack * other = NULL; 66 67 push_new(&root, &other, -5); 68 push_new(&root, &other, 1); 69 push_new(&root, &other, 8); 70 push_new(&root, &other, 0); 71 push_new(&root, &other, -1); 72 push_new(&root, &other, -7); 73 74 printf("\nMIN = %d", getMin(other)); 75 return 0; 76 }

Stack棧——getMin()