2016-04-09 15 views
0

初めてリンクされたリストを作成して、何らかの理由で予想される出力が得られません。私は他の投稿を検索し、それを引き出しましたが、まだ問題を見つけることはできません。任意の洞察が評価されます。私は頭に2を、尾に7を挿入し、メインで印刷を呼び出すと、2つしか印刷されません。リンクリストの印刷が機能していません..?

void List::print() 
{ 
if (length == 0) 
    cout << "The list is empty!" << endl; 
else 
{ 

Nodeptr temp = head; //temporary iterator 

while (temp != NULL) 
{ 
    cout << temp->data << " "; 

    temp = temp->nextNode; 
} 

    cout << endl; 
} 
} 


void List::insert_head(int data) 
{ 
if (length == 0) 
{ 
    head = new Node(data); 
    tail = head; 
} 

else 
{ 
    Nodeptr N = new Node(data); //create node by calling constructor 

    N->nextNode = head; // set new nodes next to point to current head 
    head = N; //make the head the new node 
} 

length++; 
} 

void List::insert_tail(int data) 
{ 
if (length == 0) 
{ 
    head = new Node(data); 
    tail = head; 
} 
else 
{ 
    Nodeptr N = new Node(data); 

    N->nextNode = head; 
    tail = N; 

} 

length++; //increase the list length 
} 
+0

リストとメインの定義を投稿する必要があります。 –

答えて

2

なぜ新しいノードがinsert_tail()に向いていますか?リストの最後のエントリを新しいノードにリンクする必要があります。

あなたは既に終了間際に自分のノード(7)を追加し、頭と尾の両方として(2)現在のノードを持っている:

Nodeptr N = new Node(data); 
tail->nextNode = N;  
tail = N; // now head points to 2, tail points to 7 
2

は限り私はあなたのコードを分析すると、私はLLあなたを参照してください形成された

尾である - > 7 - > 2 - > NULLヘッドが

ヘッドで

- > 2 - > NULL

insert_tailコードを

tail-> nextNode = Nと変更する必要があります。

tail = N;

は、今では頭です - > 2 - > 7 - > NULL &テール - > 7 - > NULL

が、それはあなたのお役に立てば幸い!

関連する問題