我编写了一个代码,用于创建由用户指定并打印的大小的链接列表。但我注意到了一些奇怪的行为:
如果我实现这个算法,它会正确打印一个列表:
struct num
{ int l;
num* p_next; };
void add (int size, num* head) {
srand (time(0));
for (int i = 0; i< size; i++) {
num* newnode = new num;
newnode->l = rand()%100;
newnode->p_next = head;
head = newnode;}
while (head != 0) {
cout << head->l << endl;
head = head -> p_next;}
}
int main () {
num* head = 0;
add (10, head);
}
但是,当我想通过消除内存泄漏并编写相同的任务时,使代码更安全:
struct num
{ int l;
num* p_next; };
void add (int size, num* head) {
srand (time(0));
for (int i = 0; i< size; i++) {
num* newnode = new num;
newnode->l = rand()%100;
newnode->p_next = head;
head = newnode;}
}
int extract (num*head) {
int n;
n = head->l;
head = head->p_next;
delete head;
return n;}
void print (num *head) {
while (head != 0) {
cout << extract (head) << endl;
}}
int main () {
num* head = 0;
add (10, head);
print (head);
cin.get();
cin.ignore();
}
..它不会打印任何东西。我觉得问题在于非常小的问题,但我找不到它。为什么不在第二种情况下打印它?
答案 0 :(得分:4)
您的问题是head
按值传递(是的,指针可以按值传递)到add
而不是通过引用传递。当您致电print
时,您的head
不在列表的前面(因为它在add
中没有实际修改,只有它的副本。)
试试这个:
void add (int size, num*& head)
{
srand (time(0)); //actually move this line to main, don't do it here
for (int i = 0; i< size; i++)
{
num* newnode = new num;
newnode->l = rand()%100;
newnode->p_next = head;
head = newnode;
}
}
extract
和print
编辑:您的提取功能也会不正确地删除内存。这是一个完整的工作示例:
#include <iostream>
#include <ctime>
using namespace std;
struct num
{
int l=0;
num* p_next=nullptr;
};
void add (int size, num*& head)
{
for (int i = 0; i<size; i++)
{
num* newnode = new num;
newnode->l = rand()%100;
newnode->p_next = head;
head = newnode;
}
}
int extract (num*& head)
{
int n;
n = head->l;
num* tmp = head;
head = head->p_next;
delete tmp;
return n;
}
void print (num*& head)
{
while (head != nullptr)
cout << extract(head) << endl;
}
int main ()
{
srand (time(0));
num* head = nullptr;
add (10, head);
print (head);
}
答案 1 :(得分:1)
您需要一个临时节点。您需要将temp设置为从头开始的下一个节点,然后删除head。然后将头设置为临时节点。
int extract (num*head)
{
int n;
n = head->l;
num* temp = head->p_next
delete head;
head = temp;
return n;
}