数据结构之链表实现栈

# include <stdio.h>
# include <malloc.h>
# include <stdbool.h>
typedef struct Node{
	int data;
	struct Node * next;
} Node,* PNODE;

typedef struct Stack{
	PNODE pTop;
	PNODE pBottom;
} Stack ,* PSTACK;

void init(PSTACK);
void push(PSTACK,int);
void traverse_stack(PSTACK);
bool empty(PSTACK);
void pop(PSTACK);
void clear(PSTACK);
int main(void){
	Stack stack;
	init(&stack);	
	push(&stack,12);
	push(&stack,33);
	push(&stack,22);
	push(&stack,55);
	push(&stack,77);
	traverse_stack(&stack);
	printf("--------------\n");
	pop(&stack);
	pop(&stack);
	traverse_stack(&stack);
	clear(&stack);
	printf("--------------\n");
	traverse_stack(&stack);
	printf("--------------\n");
	return 0;
}

void init(PSTACK pS){
	PNODE pNode= (PNODE)malloc(sizeof(Node));
	pS->pTop=pNode;
	pS->pBottom=pNode;
	return;
}

void push(PSTACK pS,int val){
	PNODE pNode= (PNODE)malloc(sizeof(Node));
	pNode->data=val;
	pNode->next=pS->pTop;
	pS->pTop=pNode;
	return;
}

bool empty(PSTACK pS){
	
	if(pS->pBottom == pS->pTop){
		return true;
	}	
	return false;
}



// 开始来进行遍历 
void traverse_stack(PSTACK pS){
	if(empty(pS)){
		printf("动态栈为空\n");
		return;
	}
	PNODE tmp = pS->pTop;
	while(tmp!=pS->pBottom){
		printf("动态栈中对应的内容是:%d\n",tmp->data);
		tmp=tmp->next;
	}
	return;
}

// 出栈操作 
void pop(PSTACK pS){
	if(empty(pS)){
		printf("当前栈为空\n");
		return ;
	}	
	// 开始修改对应的值
	PNODE tmp = pS->pTop; 
	pS->pTop=tmp->next;
	free(tmp);
	tmp=NULL;
}

// 一直把握不住重点! 
void clear(PSTACK pS){
	if(empty(pS)){
		printf("当前栈中已经是空的了\n");
		return;
	}else{
	PNODE q;
	// 只要当p在上面一个的时候,再次执行,就到了下一位,然后相等。所以还是指向了一个结点 
	while(pS->pTop!=pS->pBottom){
		q=pS->pTop->next;
		free(pS->pTop);
		pS->pTop=q;
	}
    }	
}
posted @ 2021-09-30 18:03  雩娄的木子  阅读(53)  评论(0编辑  收藏  举报