if
和之间有很多共同的代码else
。
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 ++;
}
在 中if
,您count
从0
增加到1
。在 中else
,您还增加了它。
count
总是在增加。所以你不需要输入两次。
if (first == NULL)
{
first->data = item;
last->data = item;
last->next = NULL;
first->next = last;
}
else
{
Node *newNode = new Node;
newNode->data = last->data;
newNode->next = last;
last->data = item;
last->next = NULL;
}
count ++;
你也在他们两个last->data
中设置item
。
而你在他们两个中都设置last->next
了NULL
。
if (first == NULL)
{
first->data = item;
first->next = last;
}
else
{
Node *newNode = new Node;
newNode->data = last->data;
newNode->next = last;
}
last->data = item;
last->next = NULL;
count ++;
new Node
当它是第一个新节点时,您还忘记创建一个。
if (first == NULL)
{
Node *newNode = new Node; // Added
first = newNode; // Added
last = newNode; // Added
first->data = item;
first->next = last;
}
else
{
Node *newNode = new Node;
newNode->data = last->data;
newNode->next = last;
}
last->data = item;
last->next = NULL;
count ++;
在first->data = item
你的if
是多余的。 first
和那里一样last
,并且last->data = item
已经在发生。
if (first == NULL)
{
Node *newNode = new Node;
first = newNode;
last = newNode;
// Removed
first->next = last;
}
else
{
Node *newNode = new Node;
newNode->data = last->data;
newNode->next = last;
}
last->data = item;
last->next = NULL;
count ++;
由于first
和newNode
具有相同的值,if
我们可以互换使用变量名。
if (first == NULL)
{
Node *newNode = new Node;
first = newNode; // These two pointers are equal!
last = newNode;
newNode->next = last; // (same pointer)
}
else
{
Node *newNode = new Node;
newNode->data = last->data;
newNode->next = last;
}
last->data = item;
last->next = NULL;
count ++;
现在,您的几乎所有内容else
也都在您的if
. 都可以搬出去。
Node *newNode = new Node;
if (first == NULL)
{
first = newNode;
last = newNode;
}
else
{
newNode->data = last->data;
}
newNode->next = last;
last->data = item;
last->next = NULL;
count ++;
该代码现在也应该更容易理解了。教训:不要重复自己。:)