数据结构之栈(Stack)的关于C语言的实现

C语言实现栈共有两种方法,一种是使用数组的包含最大Size的栈,另外一种是运用链表的方法实现

关于数组方法实现的代码如下:

#include
/**
 * Your MinStack struct will be instantiated and called as such:
 * struct MinStack* obj = minStackCreate(maxSize);
 * minStackPush(obj, x);
 * minStackPop(obj);
 * int param_3 = minStackTop(obj);
 * int param_4 = minStackGetMin(obj);
 * minStackFree(obj);
 */

typedef struct {
	int * data;
	int Top;
	int MaxSize;
    
} MinStack, * pStack;

/** initialize your data structure here. */
MinStack* minStackCreate(int maxSize) {
   pStack s= (pStack)malloc(sizeof(MinStack));
   s->data=(int)malloc(maxSize * sizeof(int));
   s->Top=-1;
   s->MaxSize=maxSize;
   return s;  
}

void minStackPush(MinStack* obj, int x) {
    obj->Top++;
	obj->data[obj->Top]=x;
}

void minStackPop(MinStack* obj) {
  obj->Top--;  
}

int minStackTop(MinStack* obj) {
    return obj->data[obj->Top];
}

int minStackGetMin(MinStack* obj) {
	int i=0;
	int re=obj->data[0];
    for(i=0;i<=obj->Top;i++){
		if(obj->data[i]data[i];
		}
	}
	return re;
}

void minStackFree(MinStack* obj) {
	int i=0;
    for(i=0;iTop;i++){
		free(obj->data[i]);
	}
	free(obj);
	obj=NULL;
}


int main(void){
	 struct MinStack* obj = minStackCreate(5);
	 minStackPush(obj,-2);
	 minStackPush(obj,0);
	 minStackPush(obj,-3);
	 printf("%d\n",minStackGetMin(obj));
	 minStackPop(obj);
	 printf("%d\n",minStackTop(obj));
	 printf("%d\n",minStackGetMin(obj));
	 
	 

	
}

关于链表的方法实现栈的代码如下:

#include
/**
 * Your MinStack struct will be instantiated and called as such:
 * struct MinStack* obj = minStackCreate(maxSize);
 * minStackPush(obj, x);
 * minStackPop(obj);
 * int param_3 = minStackTop(obj);
 * int param_4 = minStackGetMin(obj);
 * minStackFree(obj);
 
 */
typedef struct {
	int data;
	struct MinStack * next;
    
} MinStack , * Stack;

/** initialize your data structure here. */
MinStack* minStackCreate(int maxSize) {
    Stack head = (Stack)malloc(sizeof(MinStack));
	head->next=NULL;
	return head;
}

void minStackPush(MinStack* obj, int x) {
    Stack snew= (Stack)malloc(sizeof(MinStack));
	snew->data=x;
	snew->next=obj->next;
	obj->next=snew;
	
}

void minStackPop(MinStack* obj) {
    Stack q = (Stack)malloc(sizeof(MinStack));
	q=obj->next;
	obj->next=obj->next->next;
	free(q);
	q=NULL;
}

int minStackTop(MinStack* obj) {
    return obj->next->data;
}

int minStackGetMin(MinStack* obj) {
	Stack p=obj;
    int re=obj->next->data;
	while(p!=NULL){
		if(p->datadata;
		}
		p=p->next;
	}
}

void minStackFree(MinStack* obj) {
    while(obj!=NULL){
		Stack p=obj->next;
		free(obj);
		obj=p;
		
		
	}
}


int main(void){
	struct MinStack* obj = minStackCreate(10);
	int x=0;
	minStackPush(obj,-2);
	minStackPush(obj,0);
	minStackPush(obj,-3);
	x=minStackGetMin(obj);
	printf("%d",x);
	minStackPop(obj);
	x=minStackTop(obj);
	printf("%d",x);
	x=minStackGetMin(obj);
	printf("%d",x);
	
	
}

 

你可能感兴趣的:(数据结构)