2011-07-27 42 views
0

我必須編寫一個鏈表,然後將它變成一個動態堆棧,然後將其轉換爲一個動態隊列。那麼一切似乎工作,除了「出隊」,正如程序即將完成,它給了我一個錯誤:「一個未處理的Win32異常發生在LinkedList_Stack_BNS11.exe [4972]。」。LinkedList/Stack/Queue - 出隊幫助

我只是假設它是出列,因爲當我通過和/或運行程序時,它運行得很順利直到那部分,所以也許我發送了一個指針錯誤或什麼?

輸出:

Enquing 5項.... // Finsihes在隊列中分別爲(出列)

值:

//正確的編號,但是...

//程序在此處給出了該錯誤。它應該完成並關閉。

如果我包含太多的代碼,讓我知道,我會砍它歸結爲只是「出列」(這是在下面的所有東西正中)

在此先感謝您的幫助! !我只是沒有看到我做錯了什麼。認爲它可能與「頭部」指向的位置有關? IDK。

頭文件:

class NumberList 
{ 
private: 
    // 
    struct ListNode 
    { 
     int value; // Value in this node 
     struct ListNode *next; // Pointer to the next node 
    }; 

    ListNode *head; // List head pointer 
    ListNode *rear; 

public: 
    //Constructor 
    NumberList() 
    { head = NULL; rear = NULL; } 

    //Destructor 
    ~NumberList(); 

    //Stack operations 
    bool isEmpty(); 

    //Queue operations 
    void enqueue(int); 
    void dequeue(int &); 
}; 
#endif 

List_Stack_Queue.cpp:

bool NumberList::isEmpty() 
{ 
    bool status; 

    if(!head) 
     status = true; 
    else 
     status = false; 

    return status; 
} 

    void NumberList::enqueue(int num) 
    { 
     ListNode *newNode; // Point to a new node 

     // Allocate a new node and store num there. 
     newNode = new ListNode; 
     newNode->value = num; 

     //If there are no nodes in the list 
     // make newNode the first node. 
     if(isEmpty()) 
     { 
      head = newNode; 
      rear = head; 
      //newNode->next = NULL; 
     } 
     else 
     { 
      rear->next = newNode; 
      rear = rear->next; 
      //newNode->next = head; 
      //head = newNode; 
     } 
    } 

    void NumberList::dequeue(int &num) 
    { 
     ListNode *temp; 

     if(isEmpty()) 
      cout << "The queue is empty.\n"; 
     else 
     { 
      num = head->value; 
      temp = head; 
      head = head->next; 
      delete temp; 
     } 
    } 

MAIN:

const int MAX_VALUES = 3; 

// Create a DynIntQueue object. 
NumberList iQueue; 

// Enqueue a series of numbers. 
cout << "Enqueuing " << MAX_VALUES << " items...\n"; 
for (int x = 0; x < MAX_VALUES; x++) 
    iQueue.enqueue(x); 

cout << endl; 

//Dequeue and retrieve all numbers in the queue 
cout << "The values in the queue were (Dequeuing):\n"; 
while(!iQueue.isEmpty()) 
{ 
    int value; 
    iQueue.dequeue(value); 
    cout << value << endl; 
} 
return 0; 

回答

2

末節點的下一個元素應設置爲NULL在鏈接列表中。所以,

void NumberList::enqueue(int num) 
{ 
    // ... 
    if(isEmpty()) 
    { 
     head = newNode; 
     head->next = NULL; 
     rear = head; 
    } 
    else 
    { 
     rear->next = newNode; 
     rear = rear->next; 
     rear->next = NULL;  // Pointing the next node element to null. 
    } 
} 

要,我似乎有些事情是錯的Numberlist::isEmpty();成員函數。你如何決定列表是否爲空?顯示它的定義。

+0

謝謝!!你的代碼做到了,現在可以毫無錯誤地工作! :)在cpp文件中(頂部)發佈了Numberlist :: isEmpty()。 在我的任務中保存了幾個點,再次感謝:)。 問題:我現在試圖對它進行臨時化,所以我不應該發佈一個新問題,而應該編輯這個問題? – Riotson