วันอาทิตย์ที่ 29 ตุลาคม พ.ศ. 2560

C++ Stack

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
typedef struct node
{
int data;
struct node* link;
}STACK_NODE;

typedef struct
{
int count;
STACK_NODE *top;

}STACK;

void insertData(STACK* pStack);
void print(STACK* pStack);
bool push(STACK* pList, int dataIn);
bool pop(STACK* pList, int *dataOut);


int main()
{
STACK *pStack;
pStack = new STACK;
printf("=============STACK=============\n\n");
pStack->top = NULL;
pStack->count = 0;
insertData(pStack);
print(pStack);

return 0;
}

void insertData(STACK* pStack)
{
int numIn;
bool success;
srand(time(NULL));
printf("Create Number : ");
for (int nodeCount = 0; nodeCount < 10; nodeCount++)
{
numIn = rand() % 999;
printf("%4d", numIn);
success = push(pStack, numIn);
if (!success)
{
printf("Error out of memory\n");
exit(101);
}
}
printf("\n\n");
return;
}
void print(STACK* pStack)
{
int printData;
printf("Stack contained : \n");
printf("\t\t +--------+\n");
while (!pop(pStack, &printData))
{
printf("\t\t |  %4d  |\n", printData);
}
printf("\t\t +--------+\n");
return;
}
bool push(STACK* pList, int dataIn)
{
STACK_NODE* pNew;
bool success;
pNew = (STACK_NODE*)malloc(sizeof(STACK_NODE));
if (!pNew)
{
success = false;
}
else
{
pNew->data = dataIn;
pNew->link = pList->top;
pList->top = pNew;
pList->count++;
success = true;
}
return success;
}
bool pop(STACK* pList, int *dataOut)
{
STACK_NODE* pDlt;
bool success;

if (pList->top)
{
success = false;
*dataOut = pList->top->data;
pDlt = pList->top;
pList->top = (pList->top)->link;
pList->count--;
free(pDlt);
}
else
{
success = true;
}
return success;
}


ไม่มีความคิดเห็น:

แสดงความคิดเห็น