Data structure and algorithm analysis-stack (single-linked list implementation)
//by Xiabodan#include <stdio.h>#include <stdlib.h>typedef intElementType;typedef structNode *Stack;typedef structNode *position;structNode {ElementType data; Position next;};intIsEmptyStackS);voidDelete_stack (StackS);StackCreate_stack (void); ElementType Top (StackS); ElementType Pop (StackS);voidPushStackS,elementtype data);intIsEmptyStackS) {return(S->next = = NULL);}StackCreate_stack (void){StackS S = (position)malloc(sizeof(structnode));if(S = = NULL) {printf("Create_stack:out of Space");return; } s->next = NULL;//S->next is top of stack, because header can ' t store element returnS;}voidDelete_stack (StackS) {if(S = = NULL)printf("S is a empty stack!\n");Else{ while(!isempty (s)) pop (s); }}elementtype Pop (StackS) {ElementType data;if(!isempty (S)) {Position tem; TEM = s->next;//tem point to the top nodedata = s->next->data; S->next = tem->next;//also s->next = S->next->next Free(TEM);returnData }Else printf("Pop:empty stack!\n");return 0;} ElementType Top (StackS) {if(!isempty (S))return(S->next->data);printf("Top:empty stack!\n");return 0;}voidPushStackS,elementtype data) {position P; P = (position)malloc(sizeof(structnode));if(P = = NULL) {printf("Push:out of Space");return; } p->data = data; P->next = s->next;//compare list, insert node location the first node here,but insert node anywhere in listS->next = P;}intMainintARGC,Char* * argv) {StackSinti =0; ElementType data; S = Create_stack ();printf("Push datas from 0 to 9 \ n"); for(i=0;i<Ten; i++) {push (s,i); }printf("S is empty?" %d \ n ", IsEmpty (S));printf("Pop 5 datas \ n"); for(i=0;i<5; i++) {data = pop (S);printf("Pop data is:%d\n", data); }printf("Push 2 datas 11,12\n"); Push (S, One); Push (S, A);printf("Pop all remain datas \ n"); while(!isempty (S)) {data = pop (S);printf("Pop data is:%d\n", data); }printf("S is empty?" %d \ n ", IsEmpty (S)); Delete_stack (S);}
Data structure and algorithm analysis-stack