Lab_Chapter-3 :: Stack

November 21, 2012 3:38 pm C

ตัวอย่างนี้ จะเป็นการรวมการทำงานของ Stack รวมถึงทั้งการ pop และ push แล้วสั่งแสดงผลทั้งหมด

Host by img.kusumoto.co

#include <stdio.h>
/*
Kusumoto Computer Coding
http://kusumoto.co
*/
 
//void pop(NODE *head);
//void push(NODE *headNode, char data);
//void PrintStack(NODE *head);
typedef struct node {
		char data;
		struct NODE *next;
	} NODE;
 
void PrintStack(NODE *head){
	printf("\n ---------- Print Stack ------------\n");
	while(head!=NULL) {
		if(head->data!='H'){
			printf(" | %c | \n",head->data);
		}
			head = head->next;
 
		}
		printf("--------------------------");
	}
 
 
 
void push(NODE *headNode, char data){
	//create new node stack
	NODE *newStack;
	newStack = (NODE*)malloc(sizeof(NODE));
 
	//set data
	newStack->data = data;
	//link new Stack to top node
	newStack -> next = headNode->next;
 
	//link head to new top node
	headNode->next = newStack;
 
	//print push node
	printf("\n Push node | %c | In \n",newStack->data);
	PrintStack(headNode);
}
 
void pop(NODE *head) {
	//get top mode
	NODE *nodePop = head->next;
	//link head node to next node from top node
	head->next = nodePop->next;
	//print pop node
	printf("\n Pop node | %c | out \n",nodePop->data);
	//print stack
	PrintStack(head);
}
 
int main() {
 
	// declare head node
		NODE *head;
	// allocate the memory
		head = (NODE*)malloc(sizeof(NODE));
	//set the link to NULL (for now)
		head->next=NULL;
	//set data
		head->data = 'H';
	//push node
	push(head,'A');
	push(head,'B');
	push(head,'C');
	push(head,'D');
	push(head,'E');
	//pop node
	pop(head);
	pop(head);
	pop(head);
}