2016-04-27 66 views
1

我想實現一個模板單鏈表,我是相當新的C++麻煩實施模板單鏈表

#include <iostream> 
#include <string> 

#define NEWL "\n" 
#define PRINT(s) std::cout << s 
#define PRINTL(s) std::cout << s << NEWL 
#define PRINTERR(e) std::cerr << e << NEWL 

////// Class for a Node 
template<class Data> class Node { 
    Node<Data>* next_ptr; 
    Data   data; 
public: 
    Node(Node<Data>* nxt_ptr)   :next_ptr(nxt_ptr) {}; 
    Node(Data d, Node<Data>* nxt_ptr) :data(d), next_ptr(nxt_ptr) {}; 

    Node<Data>* get_next() { return next_ptr; } 
    Data&  get_data() { return data; } 

    friend std::ostream& operator<<(std::ostream& out, const Node<Data>& node) { 
     out << node.data; 
     return out; 
    }; 
}; 


////// Class for a SinglyLinkedList 
template<class Data> class SLinkedList { 
    Node<Data>* head_ptr; 
    int   max_size; 

public: 
    SLinkedList() : head_ptr(nullptr) {}; 

    bool is_empty() { 

     return head_ptr == nullptr; 

    }; 
    bool is_full() { 

     return get_size() == max_size; 

    }; 
    int get_size() { 

     if (is_empty()) { 
      return 0; 
     } 
     int count = 0; 
     for (Node<Data>* it_ptr = head_ptr; it_ptr != nullptr; it_ptr = it_ptr->get_next()) { 
      count++; 
     } 
     return count; 

    }; 
    void add(Data d) { 
     if (is_full()) { 
      throw std::exception("List is full!"); 
     } 
     Node<Data> new_node(d, head_ptr); 
     head_ptr = &new_node; 
    }; 
    void print_content() { 
     int count = 1; 
     PRINTL("This list contains:"); 
     for (Node<Data>* it_ptr = head_ptr; it_ptr != nullptr; it_ptr = it_ptr->get_next()) { 
      PRINTL("\t["<< count << "]" << " at " << it_ptr << " : " << *it_ptr); 
      count++; 
     } 
    } 
}; 

////// Main function 
int main() 
{ 

    SLinkedList<int> sll; 
    sll.add(42); 
    sll.print_content(); 

} 

我不能得到這個工作。以某種方式迭代for循環列表不起作用。它總是導致閱讀訪問衝突異常關於指向0xCCCCCCD0的指針,我不知道如何解決這個問題。

+1

我想提一下(即使已經有一個很好的答案),「0xCCCCCCD0」接近魔術調試代碼。看起來像微軟調試運行時正在告訴你,你正在使用未初始化的堆棧內存:http://stackoverflow.com/a/127404/487892認識到這些調試幻數可以幫助你在未來。 – drescherjm

回答

2

add功能是不正確

Node<Data> new_node(d, head_ptr); 

創建一個新的功能,本地Nodeadd。然後,您將head設置爲該局部變量的地址。當函數結束時,所有局部變量都被銷燬,所以現在head指向一個不再存在的對象。

若要解決此問題,您需要使用關鍵字new創建一個動態對象,該對象將在函數結束後保留​​。

Node<Data>* new_node = new Node(d, head_ptr); 
head_ptr = new_node; 

向下側,這是你必須記住調用delete所有在列表中的析構函數創建的節點。

你的代碼中還有一些其他的bug。你從來沒有在你的構造函數中設置max_size,所以除了給它一個值之外,它都是未定義的行爲,因爲我們不知道它的價值是什麼。將節點添加到列表中時,也不會增加列表的大小。

+0

就是這樣,謝謝! – blubbi