我正在学习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