數據結構算法複習[棧操作相關]

RT,純練手,記錄,不多解釋,高手飄過。

  1. //Code by Pnig0s1992 
  2. //Date:2012,3,20 
  3. #include <stdio.h> 
  4. #include <Windows.h> 
  5.  
  6. typedef struct Node * ptrNode; 
  7. typedef ptrNode Stack; 
  8. typedef int Element_type; 
  9.  
  10. struct Node{ 
  11.     Element_type Element; 
  12.     ptrNode pNext; 
  13. }; 
  14.  
  15. Stack CreateStack(void); 
  16. BOOL isEmpty(Stack S); 
  17. void MakeEmpty(Stack S); 
  18. void Push(Element_type x,Stack S); 
  19. Element_type Pop(Stack S); 
  20. void PrintStack(Stack S); 
  21.  
  22. int main(int argc,char ** argv) 
  23.     Stack pHead = CreateStack(); 
  24.     Push(20,pHead); 
  25.     Push(10,pHead); 
  26.     Push(40,pHead); 
  27.     Push(70,pHead); 
  28.     Push(50,pHead); 
  29.     Push(90,pHead); 
  30.     Push(30,pHead); 
  31.     Push(80,pHead); 
  32.     printf("\nThe stack:"); 
  33.     PrintStack(pHead); 
  34.     printf("\nThe stack after pop %d.",Pop(pHead)); 
  35.     printf("\n"); 
  36.     PrintStack(pHead); 
  37.     printf("\nThe stack is %s",isEmpty(pHead) ==TRUE ? "Empty":"Not Empty"); 
  38.     MakeEmpty(pHead); 
  39.     printf("\nAfter empty."); 
  40.     printf("\nThe stack is %s",isEmpty(pHead) ==TRUE ? "Empty":"Not Empty"); 
  41.     system("pause"); 
  42.     return 0; 
  43.  
  44. Stack CreateStack(void
  45.     ptrNode pNewNode = (ptrNode)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(Node)); 
  46.     pNewNode->pNext = NULL; 
  47.     return pNewNode; 
  48.  
  49. void Push(Element_type x,Stack S) 
  50.     ptrNode pNewNode = (ptrNode)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(Node)); 
  51.     pNewNode->Element = x; 
  52.     pNewNode->pNext = NULL; 
  53.     pNewNode->pNext = S->pNext; 
  54.     S->pNext = pNewNode; 
  55.  
  56. Element_type Pop(Stack S) 
  57.     ptrNode pTemp = S->pNext; 
  58.     Element_type x = pTemp->Element; 
  59.     S->pNext = pTemp->pNext; 
  60.     HeapFree(GetProcessHeap(),0,pTemp); 
  61.     return x; 
  62.  
  63. void PrintStack(Stack S) 
  64.     ptrNode pTemp = S->pNext; 
  65.     while(pTemp!=NULL) 
  66.     { 
  67.         printf("%d ",pTemp->Element); 
  68.         pTemp = pTemp->pNext; 
  69.     } 
  70.  
  71. BOOL isEmpty(Stack S) 
  72.     return S->pNext == NULL; 
  73.  
  74. void MakeEmpty(Stack S) 
  75.     if(isEmpty(S)) 
  76.     { 
  77.         printf("\nThe stack is empty."); 
  78.     }else 
  79.     { 
  80.         while(!isEmpty(S)) 
  81.             Pop(S); 
  82.     } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章