1、栈的定义
栈是一种特殊的线性表,他是限定仅在表尾进行插入和删除操作的线性表。
InitStack($S) //初始化一个空栈
StackEmpty(S) //判断一个栈是否为空,若栈s为空则返回true,否则返回false
Push(&S,x) //进栈,若栈 S 未满,则将x加入使之成为新栈顶
Pop(&S,&x) //出栈,若栈 S 非空,则弹出栈顶元素,并用x返
GetTop(S,&x) //读栈顶元素,若栈S非空,则用 x 返回栈顶元
DestroyStack(&S)// 销毁栈,并释放S占用的存储空间 (“&”表示引用调用)
1.2、共享栈的概念
若需要用到两个相同类型的栈,可用一个数组data[0..MaxSize-1]来实现这两个栈,这称为共享栈。(从两边向中间存储)
typedef struct
{
ElemType data[MaxSize];//存放共享栈中元素
int top1, top2; //两个栈的栈顶指针
}Dstack;
共享栈的4要素:
- 栈空条件:栈1空: top1==-1; 栈2空: top2==MaxSize;
- 栈满条件: top1==top2-1;
- 元素x进栈操作:进栈1操作: top1++;data[top1]=x; 进栈2操作:top2--;data[top2]=x;
- 元素x出栈:出栈1操作,x=data[top1];top1--; 出栈2操作,x=data[top2];top2++;
2、排序
冒泡排序
两两比较,最大的数排最后。用exchange来记录比较次序,可以在一定程度上减少比较次数
//给出关键字序列{4,5,1,2,6,3}的直接插入排序过程。
#include <stdio.h>
void BubbleSort(int a[],int n){
int i,j,exchange,bound;
exchange = n;
while(exchange){
bound = exchange;
exchange = 0;
for(i = 0;i < bound-1;i++){//注意是bound-1,否则if判断时a[i+1]会溢出
if(a[i]>a[i+1]){
j = a[i];
a[i] = a[i+1];
a[i+1] = j;
exchange = i+1;
}
}
}
}
int main() {
int i;
int a[6]={4,5,1,2,6,3};
BubbleSort(a,6);
printf("排序后的数组:");
for(i=0;i<6;i++){
printf("%d,",a[i]);
}
return 0;
}
快速排序
#include<stdio.h>
void Swap(int *a,int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int Partition(int a[],int first,int end){
int i = first;
int j = end;
while(i<j){
while(i<j&&a[i]<=a[j]) j--;
if(i<j){Swap(&a[i],&a[j]);i++;}
while(i<j&&a[i]<=a[j]) i++;
if(i<j){Swap(&a[i],&a[j]);j--;}
}
return i;
}
void QuickSort(int a[],int first,int end){
int pivot;
if(first < end){
pivot = Partition(a,first,end);
QuickSort(a,first,pivot-1);
QuickSort(a,pivot+1,end);
}
}
int main() {
int a[8] = {25,24,6,65,11,43,22,51};
int i;
printf("排序后:");
QuickSort(a,0,8-1);
for (i = 0; i < 8; i++) {
printf("%d ", a[i]);
}
}