CCI_Q3.6
本文参考该作者文章当作编程笔记: 作者:Hawstein 出处:http://hawstein.com/posts/ctci-solutions-contents.html
Q:
写程序将一个栈按升序排序。对这个栈是如何实现的,你不应该做任何特殊的假设。 程序中能用到的栈操作有:push | pop | peek | isEmpty。
思路:
需要一个额外的栈ss[1],原栈ss[0]弹出数据data,当ss[1]为空时候,直接压入;ss[1]不为空时,如果ss[1]的栈顶数据大于ss[0]弹出的数据data时,弹出ss[1]数据,压入ss[0]中,知道ss[1]中的数据不大于ss[0]弹出的data,压入data。整个过程类似,插入排序。
CODE:
1 #include<stdio.h> 2 #define N 10 3 #define less(A,B)(A<B) 4 typedef struct 5 { 6 int s[N]; 7 int top; 8 }stack_sort; 9 int isEmpty(stack_sort *ss) 10 { 11 return ss->top==-1; 12 } 13 void push(int i,stack_sort *ss) 14 { 15 if(ss->top==(N-1)) 16 return; 17 ss->s[++ss->top]=i; 18 } 19 int pop(stack_sort *ss) 20 { 21 if(isEmpty(ss)) 22 return -1; 23 return ss->s[ss->top--]; 24 } 25 int peek(stack_sort *ss) 26 { 27 if(isEmpty(ss)) 28 return -1; 29 return ss->s[ss->top]; 30 } 31 void stackSort(stack_sort *ss) 32 { 33 while(!isEmpty(ss)) 34 { 35 int data=pop(ss); 36 while(!isEmpty(ss+1) && peek(ss+1)>data) 37 { 38 push(pop(ss+1),ss); 39 } 40 push(data,ss+1); 41 } 42 } 43 void showStack(stack_sort *ss,int n) 44 { 45 int i; 46 for(i=0;i<n;i++) 47 printf("%d\t",pop(ss)); 48 printf("\n"); 49 } 50 int main() 51 { 52 stack_sort ss[2]={{{3,2,1,9,6,45,3,2},7}, 53 {{},-1}}; 54 stackSort(ss); 55 showStack(ss,2); 56 showStack(ss+1,7); 57 return 0; 58 }