下面代码中创建链表时的循环中使用了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; }
守着星空守着你
相关分类