2013-02-14 43 views
0

我一直在這一段時間了,我似乎無法弄清楚如何正確迭代我的鏈表。現在,我可以運行該程序,並運行它,但我沒有從鏈接列表中獲得任何結果。這是我的代碼到目前爲止 這裏是應該發生的事情。 enter image description here無法遍歷我的鏈表在c + +

這是我的結果。 enter image description here但是,這也崩潰馬上

#ifndef LList_h 
#define LList_h 

#include <iostream> 
#include "node.h" 

class LList 
{ 
public: 
    LList(void);   //constructor 
    LList(const LList &); //copy constructor 
    ~LList();   //destructor 

    LList *next;   //points to next node 
    void push_back(const string &str); 
    void push_front(const string &str); 
    friend ostream& operator<<(ostream& out, const LList& llist); 
    LList &operator=(const LList &l);  
private: 
    Node *_head; 
    Node *_tail; 

    string _str; 
}; 

inline LList::LList(void) { 
    cerr << "head = tail = 0 at 0024f8d0\n"; 

    _head = 0; 
    _tail = 0; 
} 

inline void LList::push_back(const string &_str) { 
    Node *p = new Node(_str); 
    if (_tail == 0) { 
     _tail = p; 
    } else { 
     _tail ->next(p); 
     _tail = p; 
    }   
} 

inline void LList::push_front(const string &_str) { 
    Node *p = new Node(_str); 

    if (_head == 0) { 
     _head = p; 
    } else { 
     _head ->next(p); 
     _head = p; 
    } 
} 

ostream &operator <<(ostream &out, const LList & llist) { 
    for(LList *p = llist.front; p != 0; p = p -> next) 
     out << p; 

    return out; 
} 

LList & LList::operator=(const LList &l) { 
    _head = 0; 
    _tail = 0; 

    return *this; 
} 
#endif 
+4

請將您的代碼降低到顯示您的問題所需的最小量。 – thiton 2013-02-14 13:36:19

+0

會發生什麼?應該發生什麼? – dutt 2013-02-14 13:39:18

+0

您好,最好是將錯誤實際粘貼到「代碼」塊中,以便Google抓取工具可以爲出現類似問題的用戶索引此頁面。屏幕截圖不是最佳的。 – 2013-02-14 13:45:29

回答

0

什麼是Node::next(Node *p)功能嗎? 如果設置的this的下一場p,那麼這段代碼在你的push_front功能可能是錯誤的:

else 
{ 
    _head ->next(p); 
    _head = p; 
} 

而是應該:

  1. 設置p.next_head。 (現在頭如下p
  2. set _head to p。 (新的頭是p
+0

究竟是怎麼回事,那麼它應該看起來像這樣,然後'p.next = _head'和'_head = p' – beginnerprogrammer 2013-02-14 14:14:15

+0

是的,(15 char限制令人討厭)。 – Ben 2013-02-14 14:19:14

+0

好吧,但是當我嘗試這樣做時,我收到一條錯誤消息,說「節點* p錯誤:表達式必須具有類類型」 – beginnerprogrammer 2013-02-14 14:21:22

1

看來您的原始代碼可能存在多個問題。鑑於上面的討論和一些答覆,我建議從簡單的事情開始。得到這個工作,然後逐漸擴大它,直到你有了你最初的目標。

我會開始實現一個非常簡單的單鏈表而不使用類。定義一個包含指向相同類型和數據字段的結構的指針的結構(可以只是一個整數)。

創建此結構的三個左右變量並將它們鏈接在一起,使第一個指向第二個,第二個指向第三個,第三個指向NULL(通過它可以識別列表的結尾)。

然後演示遍歷列表。 C中的一個很常見的成語是:

for (ptr = &first; ptr; ptr = ptr->next) 
{ 
    printf("%p %d\n", ptr, ptr->data); 
} 

確保你明白爲什麼這個工程,並用它來獲得舒適的使用指針以及如何鏈表工作。練習使用調試器單步執行您的列表,並確保您瞭解到達列表末尾時循環終止的方式。

一旦您對此感到滿意,無論如何將它包裝在類中並添加push_back()和push_front()等方法,並重載某些運算符。

但首先確保您的基礎知識紮實。

+0

是的,我想是的。 – Ben 2013-02-14 14:42:48

+0

我希望我有更多時間這樣做。我儘量抽出時間,但一天中沒有足夠的時間給我。 – beginnerprogrammer 2013-02-14 14:50:06

+0

@JohnTinio我很同情。儘管如此,沒有人成爲一名優秀的程序員。堅持下去。 – 2013-02-14 15:17:59