栈的操作,创建,遍历,入栈,出栈

<pre name="code" class="cpp"><pre name="code" class="cpp">#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

typedef struct node{
	int data;
	struct node *pNext;
}NODE, *PNODE;

typedef struct stack{
	PNODE pTop;
	PNODE pBottom;	
}STACK, *PSTACK;


void init(PSTACK s);
void push(PSTACK s, int val);
void traverse(PSTACK s);
bool pop(PSTACK s, int* val);
void clean(PSTACK s);

int main(void){
	STACK s;
	int val;
	init(&s);
	push(&s,1);
	push(&s,2);
	push(&s,3);
    traverse(&s);
    if(pop(&s,&val)){
    	printf("弹出成功!被弹出的元素是:%d\n",val);
    }
    else{
		printf("弹出失败!"); 
	} 
    
    traverse(&s);
    clean(&s);
	return 0;
}
void init(PSTACK pS){
	pS->pTop = pS->pBottom = (PNODE)malloc(sizeof(NODE));
	///pS->pTop->pNext = NULL;
	pS->pBottom->pNext = NULL;
	return;
}
void push(PSTACK pS,int val){
	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	pNew->data = val;
	pNew->pNext = pS->pTop;  //pS->Top不能改成pS->Bottomb不然新节点下一个总是指向栈底了 
	pS->pTop = pNew;	
}
void traverse(PSTACK pS){
	PNODE p = pS->pTop;
	while(p->pNext != NULL){  //这里也可以写成while(p != pS->pBottom) 
		printf("%d\t",p->data);
		p = p->pNext;
	}
	printf("\n");
	return;
}
bool pop(PSTACK pS,int *val){
	if(pS->pTop != NULL){
	PNODE p = pS->pTop;
	pS->pTop = p->pNext;
	*val = p->data;
	free(p);
	p = NULL;  //这个漏掉了 
	return true;	
	}
	else 
	    return false;
	
}
void clean(PSTACK pS){ 
	PNODE p = pS->pTop;
	PNODE q = NULL;
	while(p->pNext != NULL){  //这里也可以写成while(p != pS->pBottom)
		q = p->pNext;
		free(p);
		q = p;
		//这里需要一个q指针始终指向p指向的下一个节点,这样来释放内存空间 
		 
	}
	pS->pTop = pS->pBottom; 
} 


 
 
 
 

      栈的操作,创建,遍历,入栈,出栈_第1张图片

   

你可能感兴趣的:(栈的操作,创建,遍历,入栈,出栈)