데이터 구조 초학 - 스 택 의 기본 조작

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

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

void init(PSTACK);
void push(PSTACK, int); 
void traverse(PSTACK);
bool pop(PSTACK, int *); 
void clear(PSTACK pS);

int main(void)
{ 
	STACK S;//STACK      struct Stack;
    int val;
	 
	init( &S);//          
	push(&S, 1);//   
	push(&S, 2);
	push(&S, 3);
	push(&S, 4);
	push(&S, 5);
	push(&S, 6);
	traverse(&S); //     
	
	if( pop(&S, &val) )//  
	{
		printf("    ,      %d
", val); } else { printf(" !
"); } traverse(&S); clear(&S); traverse(&S); if( pop(&S, &val) )// { printf(" , %d
", val); } else { printf(" !
"); } return 0; } void init(PSTACK pS) { pS->pTop = (PNODE)malloc(sizeof(NODE)); if(NULL == pS->pTop) { printf(" !
"); exit(-1); } else { pS->pBottom = pS->pTop; 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.pBottom; pS->pTop = pNew; return; } void traverse(PSTACK pS) { PNODE p = pS->pTop; while(p != pS->pBottom) { printf("%d ", p->data); p = p->pNext; } printf("
"); return; } bool empty(PSTACK pS) { if(pS->pBottom == pS->pTop) return true; else return false; } // pS , pVal 。 , false, true。 bool pop(PSTACK pS, int *pVal) { if(empty(pS))//pS S { return false; } else { PNODE r = pS->pTop; *pVal = r->data; pS->pTop = r->pNext; free(r); r = NULL; return true; } } //clear void clear(PSTACK pS) { if(empty(pS)) { return; } else { PNODE p = pS->pTop; PNODE q = NULL; while(pS ->pBottom != p) { q = p ->pNext; free(p); p = q; } pS ->pTop = pS->pBottom; } }

좋은 웹페이지 즐겨찾기