ltbaogt
Tổng số bài gửi : 18 Join date : 01/01/2010
| Tiêu đề: Stack va Queue Mon Apr 12, 2010 3:11 pm | |
| - Code:
-
#include <stdio.h> struct NODE{ int Key; NODE *pNext; }; NODE* CreateNode(int Data) { NODE* pNode; pNode = new NODE; if (pNode == NULL) return NULL; pNode->Key = Data; pNode->pNext = NULL; return pNode; } bool AddHead(NODE* &pHead, int Data) { NODE *pNode; pNode = CreateNode(Data); if (pNode == NULL) return false; if (pHead == NULL) pHead = pNode; else { pNode->pNext = pHead; pHead = pNode; } return true; } NODE* RemoveHead(NODE* &pHead) { if(pHead == NULL) return NULL; NODE* pResult = pHead; pHead = pHead->pNext; return pResult; } NODE* RemoveTail(NODE* &pHead) { NODE *pNode; if(pHead == NULL) //<1> khong phan tu { return NULL; } else if(pHead->pNext == NULL) //<2> Neu danh sach chi co 1 phan tu la pHead thi thuc hien { pNode = pHead; pHead = NULL; return pNode; } pNode = pHead; while(pNode->pNext->pNext != NULL) //<3> tim phan tu ke phan tu cuoi { pNode = pNode->pNext; } NODE* pResult = pNode->pNext; pNode->pNext = NULL; return pResult; } //-------STACK : //----PUSH tuong ung AddHead //----POP tuong ung RemoveHead bool PushStack(NODE* &pStack, int Data) { return AddHead(pStack, Data); } NODE* PopStack(NODE* &pStack) { return RemoveHead(pStack); } //--------QUEUE : //----ENQUEUE tuong ung AddHead //----DEQUEUE tuong ung RemoveTail bool EnQueue(NODE* &pQueue, int Data) { return AddHead(pQueue, Data); } NODE* DeQueue(NODE* &pQueue) { return RemoveTail(pQueue); } void main() { int n; NODE* pStack = NULL; NODE* pQueue = NULL;
for(int i=0;i<3;i++) { printf("Nhap Key cua Node: "); scanf("%d",&n); PushStack(pStack,n); EnQueue(pQueue,n);
} for(int j=0;j<4;j++ ) { NODE* pnode=PopStack(pStack); if(pnode!=NULL) { printf(" %d \n",pnode->Key);
} else { printf("NULL "); } } /* if(pNode!=NULL) { printf("\nPhan Tu Stack Lay ra la:%d\n",pNode->Key); } else { printf("\nStack Rong "); } if(pNode2!=NULL) { printf("\nPhan Tu Queue Lay ra la:%d\n",pNode2->Key); } else { printf("\nQueue Rong \n"); } */ } /* NODE* pStack = NULL; NODE* pQueue = NULL; int n = 1; while(n!=0) { PushStack(pStack, n); EnQueue(pQueue, n); n--; } NODE* pNode = DeQueue(pQueue); if(pNode != NULL) //<4> printf("\nGia tri phan tu (Queue) : %d\n", pNode->Key); else printf("\nNULL\n"); NODE* pNode2 = PopStack(pStack); if(pNode2 != NULL) printf("\nGia tri phan tu (Stack) : %d\n", pNode2->Key); else printf("\nNULL\n"); */ | |
|