关于c++中的错误。。

来源:百度知道 编辑:UC知道 时间:2024/05/14 15:21:03
这是头文件。。
#ifndef LINKEDLIST_H
#define LINKEDLIST_H

#include<iostream>
using namespace std;

struct LinkNode
{
int data;
LinkNode *link;
};

class List
{
private:
LinkNode *first;
int length;
public:
List();
void Insert(int x);
void getList();
};

List::List()
{
length = 0;
first->link =0;
}

void List::Insert(int x)
{
LinkNode *p,*newNode;
newNode = new LinkNode;
newNode->data = x;
newNode->link = 0;
p = first;
for(int i = 1; i <= length; i ++)
p = p->link;
p->link = newNode;
length ++;

}

void List::getList()
{
LinkNode *p;
p = first->link;
for(int i = 1; i <= length; i++)
{
cout<<p->data<<" ";
p = p->link;
}
cout<<endl;
}

#include "stdafx.h"
#include <iostream>
#include <conio.h>

using namespace std;

struct LinkNode
{
int data;
LinkNode *link;
};

class List
{
private:
LinkNode *first;
int length;
public:
List();
void Insert(int x);
void getList();
};

List::List()
{
length = 0;
first = new LinkNode;//错误所在,first始终没有初始化。以致头结点失踪为空,是得->link始终为空。
}
void List::Insert(int x)
{
LinkNode *p,*newNode;
newNode = new LinkNode;
newNode->data = x;
newNode->link = 0;
p = first;
for(int i = 1; i <= length; i ++)
p = p->link;
p->link = newNode;
length ++;

}
void List::getList()
{
LinkNode *p;
p = first->link;
for(int i = 1; i <= length; i++)
{
cout<<p->data<<" ";
p = p->link;