我正在用C ++开发链表。使用delete
时出现问题。
我从程序参数中读取了许多元素。我可以创建它们。我可以列出它们。当我使用delete
时,代码不起作用。
我是否必须使用delete
?
#include <iostream>
#include <sstream>
struct element {
int value;
element *next;
};
int main(int argc, char **argv) {
int num;
std::stringstream ss;
if (argc >= 2) {
std::cout << argv[0] << std::endl;
ss << argv[1];
ss >> num;
std::cout << "You want: " << num << " numbers" << std::endl;
} else {
std::cout << "Error" << std::endl;
}
element *first = NULL;
element *current = NULL;
// creating
for(int i=0; i<num; i++) {
element *elem = new element();
if( first == NULL ) {
first = elem;
}
elem -> value = i;
elem -> next = NULL;
if( current == NULL ) {
current = elem;
} else {
current -> next = elem;
current = elem;
}
}
// printing
current = first;
while( current ) {
std::cout << "value: " << current -> value << std::endl;
current = current -> next;
}
// removing
current = first;
while( current ) {
delete current;
current = current -> next;
}
delete first;
}
我想要的是打印所有元素。我知道每个new
都应附有delete
,但是我的代码有问题。
答案 0 :(得分:0)
我已根据@Yksisarvinen注释修复了我的代码。现在可以使用了。谢谢!
#include <iostream>
#include <sstream>
struct element {
int value;
element *next;
};
int main(int argc, char **argv) {
int num;
std::stringstream ss;
if (argc >= 2) {
std::cout << argv[0] << std::endl;
ss << argv[1];
ss >> num;
std::cout << "You want: " << num << " numbers" << std::endl;
} else {
std::cout << "Error" << std::endl;
}
element *first = NULL;
element *current = NULL;
// creating
for(int i=0; i<num; i++) {
element *elem = new element();
elem -> value = i;
elem -> next = NULL;
if( current == NULL ) {
first = elem;
current = elem;
} else {
current -> next = elem;
current = elem;
}
}
// printing
current = first;
while( current ) {
std::cout << "value: " << current -> value << std::endl;
current = current -> next;
}
// removing
current = first;
while( current ) {
element *to_remove = current;
current = current -> next;
delete to_remove;
}
}