2015-02-06 11 views
2

作爲數據結構的學校任務的一部分,我必須編寫一個程序來實現堆棧作爲鏈接列表。以下是我寫的代碼。菜單驅動程序堆棧作爲鏈接列表與char信息

C++程序要使用鏈表

#include<iostream.h> 
    #include<stdlib.h> 
    #include<stdio.h> 
    #include<string.h> 

    /* 
    * Node Declaration 
    */ 
    struct node 
    { 
     char city[20]; 
     struct node *link; 
    }*top; 

    /* 
    * Class Declaration 
    */ 
    class stack_list 
    { 
     public: 
     node *push(node *, char[20]); 
     node *pop(node *); 
     void traverse(node *); 
     stack_list() 
     { 
      top = NULL; 
     } 
    }; 

    /* 
    * Main: Contains Menu 
    */ 
    int main() 
    { 
     int choice; 
     char item[20]; 
     stack_list sl; 
     do 
     { 
     cout<<"\n-------------"<<endl; 
     cout<<"Operations on Stack"<<endl; 
     cout<<"\n-------------"<<endl; 
     cout<<"1.Push Element into the Stack"<<endl; 
     cout<<"2.Pop Element from the Stack"<<endl; 
     cout<<"3.Traverse the Stack"<<endl; 
     cout<<"4.Quit"<<endl; 
     cout<<"Enter your Choice: "; 
     cin>>choice; 
     switch(choice) 
     { 
     case 1: 
      cout<<"Enter value to be pushed into the stack: "; 
      gets(item); 
      top = sl.push(top, item); 
      break; 
     case 2: 
      top = sl.pop(top); 
      break; 
     case 3: 
      sl.traverse(top); 
      break; 
     case 4: 
      exit(1); 
      break; 
     default: 
      cout<<"Wrong Choice"<<endl; 
     } 
     } while(choice !=4); 
     return 0; 
    } 

    /* 
    * Push Element into the Stack 
    */ 
    node *stack_list::push(node *top, char city[20]) 
    { 
     node *tmp=NULL; 
     tmp = new (struct node); 
     strcpy(tmp->city,city); 
     // tmp->city[20] =item[20]; 
     tmp->link = top; 
     top = tmp; 
     return top; 
    } 

    /* 
    * Pop Element from the Stack 
    */ 
    node *stack_list::pop(node *top) 
    { 
     node *tmp; 
     if (top == NULL) 
      cout<<"Stack is Empty"<<endl; 
     else 
     {  
      tmp = top; 
     cout<<"Element Popped: "<<tmp->city<<endl; 
      top = top->link; 
      free(tmp); 
     } 
     return top; 
    } 

    /* 
    * Traversing the Stack 
    */ 
    void stack_list::traverse(node *top) 
    {  
     node *ptr; 
     ptr = top; 
     if (top == NULL) 
      cout<<"Stack is empty"<<endl; 
     else 
     { 
      cout<<"Stack elements :"<<endl; 
      while (ptr != NULL) 
      { 
      cout<<ptr->city[20]<<endl; 
       ptr = ptr->link; 
      } 
     } 
    } 

下面的程序不顯示運行期間按壓的字符實現堆棧。 如果我推「德里」,我會被推動並彈出,但當我稱橫向時,它不會顯示推動的成員。

回答

2

此行是錯誤的:

 cout<<ptr->city[20]<<endl; 

您需要使用:

 cout<<ptr->city<<endl; 

建議改變stack_list

而不是使用一個全球top的,讓一個成員變量top在課堂裏。然後,您可以簡化成員函數。他們不需要node*作爲輸入。

class stack_list 
{ 
    public: 
    node *push(char[20]); 
    node *pop(); 
    void traverse(); 
    stack_list() 
    { 
     top = NULL; 
    } 
    private: 
     node* top; 
}; 

相應地更改實現。