我正在學習C++。我正在創建一個鏈表數據結構。顯示結構中節點值的函數之一不起作用。出於某種原因,遍歷節點的while循環在顯示函數中不起作用,因此我看不到這些節點中的值。有沒有人看到問題是什麼?我一直在盯着代碼一段時間,不知道這裏有什麼問題。 感謝您的幫助提前。 頭文件:基本C++編程問題
// linklist.h
// class definitions
#ifndef LINKLIST_H
#define LINKLIST_H
class linklist
{
private:
// structure containing a data part and link part
struct node
{
int data;
node *link;
}*p;
public:
linklist();
void append(int num);
void addatbeg(int num);
void addafter(int loc, int num);
void display();
int count();
void del(int num);
~linklist();
};
#endif
.cpp file
// LinkedListLecture.cpp
// Class LinkedList implementation
#include"linklist.h"
#include<iostream>
using namespace std;
// initializes data member
linklist::linklist()
{
p =NULL;
}
// adds a node at the end of a linked list
void linklist::append(int num)
{
node *temp, *r;
// if the list is empty, create first node
if(p==NULL)
{
temp = new node;
temp->data = num;
temp->link = NULL;
}
else
{
// go to last node
temp = p;
while(temp->link!=NULL)
temp = temp->link;
// add node at the end
r = new node;
r->data=num;
r->link=NULL;
temp->link=r;
}
}
// displays the contents of the linked list
void linklist::display()
{
node *temp = p;
cout<< endl;
// traverse the entire linked list
while(temp!=NULL) // DEBUG: the loop doesn't work
{
cout<<temp->data<<" ";
temp = temp->link;
}
void main()
{
linklist l;
l.append(14);
l.append(30);
l.append(25);
l.append(42);
l.append(17);
cout<<"Elements in the linked list:";
l.display(); // this function doesn't work
system("PAUSE");
}
它以什麼方式「不起作用」?期望的輸出是什麼,你取而代之的是什麼? (還要記住,當你轉移到真正的生產代碼時,最好使用標準庫附帶的鏈表,'std :: list') – 2011-05-29 02:52:34
[GWW's answer](http:// stackoverflow。 com/questions/6165674/basic-c-programming-question/6165685#6165685)強調它不是'display()',而是'append()'引起你的悲傷。一旦你解決了這個問題,你可能想要爲每個'new'添加一個'delete',去除[內存泄漏](http://en.wikipedia.org/wiki/Memory_leak)。 – Johnsyweb 2011-05-29 03:06:21