【发布时间】:2013-04-09 02:51:04
【问题描述】:
我的 add 函数显然有问题,因为它首先取消引用,因此首先指向任何内容。我只是不知道如何修复它,使其不是空指针。
struct Node
{
int data;
Node *next;
};
class LinkedList
{
Node *first;
Node *last;
int count;
public:
LinkedList()
{
first = NULL;
last = NULL;
count = 0;
}
void Add(int item)
{
if (first == NULL)
{
first->data = item;
last->data = item;
last->next = NULL;
first->next = last;
count = 1;
}
else
{
Node *newNode = new Node;
newNode->data = last->data;
newNode->next = last;
last->data = item;
last->next = NULL;
count ++;
}
}
【问题讨论】:
-
如果您不希望
first为空,请将其指向某个对象。您已经知道如何创建Node(如您的else块中所示),所以:first = new Node;。 -
你的条件是
if first is null, then use first。这是不正确的。如果first为 null,则不能使用它。 -
你是认真的吗?再开一个帖子怎么样?
-
@BdkFivehunna 我将您的问题回滚到其原始形式。如果您有不同的问题,请提出一个新问题。不要替换现有的问题。这样做会使所有的 cmets 和答案看起来毫无意义。
-
@BdkFivehunna 请停止替换您的问题。
标签: c++