我不明白爲什麼display()func只顯示列表的第一個成員。我認爲我做了一些亂七八糟的指針,但我不明白在哪裏。我已經將它與其他鏈表源進行了比較,它似乎是以良好的方式編寫的。C++鏈接列表打印錯誤
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
struct Node
{
int Data;
Node * next;
};
void initNode(struct Node *head,int n);
void AddNode(int n,Node* head);
void display(Node* head);
int main()
{
Node * head = new Node;
initNode(head,5);
display(head);
AddNode(10,head);
display(head);
AddNode(15,head);
display(head);
cin.get();
return 0;
}
void AddNode(int n,Node * head)
{
Node * node = new Node;
node->Data = n;
node->next = NULL;
Node * nextNode = head;
while(nextNode)
{
if(nextNode->next == NULL)
{
nextNode->next = node;
}
nextNode = nextNode->next;
}
}
void display(Node * head)
{
while(head)
{
cout << head->Data << " "<<endl;
head = head->next;
}
}
void initNode(struct Node *head,int n)
{
head->Data = n;
head->next = NULL;
}
這是不同的。您的函數在開始時添加節點,而OP會在最後添加它們。通常,如果可能,最好在開始時添加,但我們不知道OP需要什麼。 – interjay
@interjay - 謝謝。我已經更新了答案 – Sean