2016-08-24 93 views
-2

所以我想獲得鏈接列表,這是我的代碼到目前爲止。當我在列表的前面添加節點時,一切看起來都很好,但是當我嘗試在後面添加我的第一個節點時,我的代碼編譯但返回-1。我不確定它有什麼問題,但我知道它在insertBack()函數中。順便說一句,如果還有什麼不對,請讓我知道,這是我第一次嘗試鏈接列表! 謝謝!鏈接列表不工作在c + +

#include "LinkedList.h" 
#include <iostream> 
#include <stddef.h> 

LinkedList::LinkedList() 
{ 
    head=NULL; 
    length=0; 
} 

void LinkedList::InsertFront(int item) 
{ 
    Node *temp = new Node; 
    temp->data = item; 
    temp->next = head; 
    head = temp; 
    length++; 
} 

void LinkedList::InsertBack(int item) 
{ 
    Node *temp1 = new Node; 
    temp1 = head; 

    while(temp1->next != NULL) 
    { 
     temp1 = temp1->next; 
    } 
    Node *temp = new Node; 
    temp->data = item; 
    temp->next = NULL; 
    temp1->next = temp; 

    length++; 
} 

void LinkedList::MakeEmpty() 
{ 
    Node *temp; 
    while(head!= NULL) 
    { 
     temp = head; 
     head = head->next; 
     delete temp; 
    } 
    length; 
} 

void LinkedList::ShowItems() 
{ 
    Node *temp = head; 
    while(temp != NULL) 
    { 
     std::cout<<temp->data<<std::endl; 
     temp = temp->next; 
    } 
} 


LinkedList::~LinkedList() 
{ 
    MakeEmpty(); 
} 
+2

你還應該從這個千年獲得一些學習材料/告訴你的老師80年代已經過去了。 –

+1

你應該看看「資源獲取初始化」(RAII)以及**現代** C++中所有可愛的指針現代風格。這是一個很好的開始:http://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c – Matt

+0

哈哈好吧!哇謝謝...! –

回答

1

確保在引用它之前分配了頭部。當你運行InsertBack時,這是你問題的最可能的來源,這取決於頭已經被初始化了,因爲它從第一個元素開始遍歷列表中的所有元素,但是假定第一個元素已經被分配。

它也會產生不必要的內存分配 - 它會創建一個新的節點,然後立即寫入指向它的東西,那麼重點是什麼?

Node *temp1 = new Node; 
temp1 = head; 
+0

謝謝!這說得通!我會試試看 –