题目描述下面代码中创建链表时的循环中使用了new,如何设置对应的delete释放内存?PS.代码中自己的delete位置好像不对,也搜到过说小程序delete不delete不影响这种说法。求教大神!相关代码//链表测试#include <iostream>#include <stdlib.h> struct Node {public: int data;
Node *pNext;
};//int main(){ //头结点
Node *head;
head = new Node;
head->data = 0;
head->pNext = NULL; //创建链表
Node *pnew, *ptemp;
ptemp = head; int n = 0; std::cout << "请输入需要创建单向链表的结点个数:"; std::cin >> n; int i = n; while (n > 0) {
n--;
pnew = new Node; std::cout << "输入第" << i - n << "个结点值:"; std::cin >> pnew->data;
pnew->pNext = NULL;
ptemp->pNext = pnew;
ptemp = pnew;
} //打印链表
std::cout << "打印链表值如下:";
Node *p = head->pNext;
while (p != NULL) { std::cout << p->data << " ";
p = p->pNext;
} std::cout << std::endl; delete head; delete pnew; return 0;
}
1 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
补充释放内存代码
std::cout << "释放链表内存:"; p = head->pNext; while (p != NULL) { ptemp = p; std::cout << p->data << " "; p = p->pNext; delete ptemp; } std::cout << std::endl;
- 1 回答
- 0 关注
- 893 浏览
添加回答
举报
0/150
提交
取消