堆的實現

諸葛倫發表於2015-05-08


#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

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

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

void init(PSTACK pS)
{
 pS->pTop = (PNODE)malloc(sizeof(NODE));
 if (NULL == pS->pTop)
 {
  cout << "動態記憶體分配失敗" << endl;
  exit(-1);
 }
 else
 {
  pS->pBotton = pS->pTop;
  pS->pTop->pNext = NULL;
 }
}

void push(PSTACK pS, int val)
{
 PNODE pNew = (PNODE)malloc(sizeof(NODE));
 if (NULL == pNew)
 {
  cout << "動態記憶體分配失敗" << endl;
  exit(-1);
 }
 pNew->data = val;
 pNew->pNext = pS->pTop;
 pS->pTop = pNew;

 return;
}

void traverse(PSTACK pS)
{
 PNODE p = pS->pTop;

 while (p != pS->pBotton)
 {
  cout << p->data << "    ";
  p = p->pNext;
 }
 return;
}
bool empty(PSTACK pS)
{
 if (pS->pBotton == pS->pTop)
  return true;
 else
  return false;
}
bool pop(PSTACK pS, int * val)
{
 if (empty(pS))
 {
  return false;
 }
 else
 {
  PNODE r = pS->pTop;
  *val = r->data;
  pS->pTop = r->pNext;
  free(r);
  r = NULL;
 }
 return true;
}
void clear(PSTACK pS)
{
 while (pS->pTop != pS->pBotton)
 {
 PNODE r = pS->pTop;
 pS->pTop = r->pNext;
 free(r);
 r = NULL;
 }
 /*if (empty(pS))
 {
  return;
 }
 else
 {
  PNODE p = pS->pTop;
  PNODE  q = NULL;
  while (p != pS->pBotton)
  {
   q = pS->pTop->pNext;
   free(p);
   p = q;
  }
  pS->pTop = pS->pBotton;
 }*/
}
int main()
{
 STACK S;
 int pVal;
 init(&S);
 push(&S,1);
 push(&S,2);
 push(&S, 3);
 push(&S, 4);
 push(&S, 5);
 push(&S, 6);
 push(&S, 7);
 push(&S, 8);
 traverse(&S);

 if (pop(&S, &pVal))
 {
  cout << "出棧成功" << "出棧的是:" <<pVal<<endl;
 }
 else
 {
  cout << "出棧失敗" << endl;
 }
 traverse(&S);
 clear(&S);
 traverse(&S);
 system("pause");
 return(0);
}


相關文章