机试常用数据结构
北航的机试要求用标准C编程,所以很多C++的库都没法用。因此我使用最简单的代码实现了几个常见的数据结构。标准C库参考:
http://wiki.jikexueyuan.com/project/c/c-standard-library.html
1. 数组实现的栈。此处栈的元素默认为int, 也可以改为其他。
struct Stack{
int buf[100]; //大小为100的栈
int top; //标记栈的顶点;
//初始化,使用栈时必须先初始化
void init(){
top=0;
}
void push(int x){
buf[top++]=x;
}
int pop(){
return buf[--top];
}
bool isEmpty(){
if(top==0) return true;
else return false;
}
bool isFull(){
if(top==100) return true;
else return false;
}
};
2. 优先队列。优先队列有多种实现方式,最简单的是链表实现。链表实现又可以分两种:一种是每次push都放在表头(O(1)),pop时遍历整个链表找出最小值弹出(O(n));另一种是总维持一个有序的链表,push时需要遍历链表(O(n)),pop只需弹出表头(O(1))。考虑到实现复杂度以及push的次数总大于等于pop()次数。故选取第一种实现方式。
/*
优先队列:简单链表实现
*/
#include<stdio.h>
#include<stdlib.h>
#define len sizeof(node)
#define MAX 99999;
struct node{
int x;
node* next;
};
struct queue{
node * head; //链表头
void init(){
head=NULL;
}
node* create(int x){
node* p=NULL;
p=(node*)malloc(len);
if(p==NULL){
printf("malloc fail!");
}
p->x=x;
p->next=NULL;
return p;
}
void push(int x){
node *p=create(x);
p->next=head;
head=p;
}
bool isEmpty(){
if(head==NULL)
return true;
else
return false;
}
int pop(){
node *p, *q, *tmp, *tmq;
int min=MAX;
//找到最小点
p=head;
q=tmp=tmq=NULL;
while(p!=NULL){
if(p->x < min){
tmp=p;
tmq=q;
min=p->x;
}
q=p;
p=p->next;
}
if(tmq==NULL){
head=tmp->next;
}else{
tmq->next=tmp->next;
}
free(tmp);
return min;
}
};
int main(){
int n; //指令:0退出并弹出队列中所有元素;1为插入元素;2为弹出元素
queue q;
q.init();
while(scanf("%d", &n)!=EOF && n!=0){
if(n==1){
int tmp;
scanf("%d", &tmp);
q.push(tmp);
}else{
int tmp;
if(q.isEmpty()){
printf("heap is NULL!\n");
}else{
tmp=q.pop();
printf("top of the heap: %d\n", tmp);
}
}
}
while(!q.isEmpty()){
int tmp;
tmp=q.pop();
printf("%d ", tmp);
}
printf("\n");
return 0;
}
样例:
输入 | 输出 |
---|---|
1 2 1 3 1 0 1 4 2 0 | the top of the heap: 0 2 3 4 |
注意:malloc 和free 函数的使用