1

我用过的编译器都不能调试它。我正在尝试在列表末尾添加一个新节点,然后显示它,它们没有显示任何类型的错误,两者都给出了发送不发送窗口的错误,我认为这可能是内存泄漏..请帮我

#include <iostream>
#include <conio.h>
using namespace std;

struct Node
{
    int data;
    Node *nextptr;
};


class CLLIST{

private:
    Node*firstptr;
    Node*lastptr;

public:
     CLLIST(){

     cout << "Constructor Called !";
      firstptr=lastptr=NULL;
}

 void insert_at_back(int val){
     cout << " \n \n I am in the insert at back function: ";
     Node*newptr;
     newptr = new Node;
     newptr->data=val;

     if(firstptr=NULL)//means list is empty
     {
         firstptr=newptr;

     }else{
         lastptr->nextptr=newptr;
     }

     lastptr=newptr;
     lastptr->nextptr=firstptr;
 }

 void display(){

     Node *temptr,*endptr;
     temptr = new Node;
     endptr = new Node;

     temptr=firstptr;
     endptr = NULL;
     while(temptr!=endptr){

         cout << "I am in the display Function: ";
         cout << firstptr->data << " ";
         firstptr=firstptr->nextptr;
         endptr=firstptr;}

         delete temptr;
         delete endptr;
     }


 };





 int main()
 {
 CLLIST obj1;




  obj1.insert_at_back(26);

  obj1.display();

 cout << " \n \n Done !";

getch();
 }
4

1 回答 1

0

诱惑=第一点;endptr = NULL; 而(temptr!=endptr){

     cout << "I am in the display Function: ";
     cout << firstptr->data << " ";
     firstptr=firstptr->nextptr;
     endptr=firstptr;}

     delete temptr;
     delete endptr;
 }

您在 while 条件下将 tempptr 与 endptr 进行比较,但您永远不会重新分配 tempptr,因为在开始时 tempptr = firstptr,然后 firstptr 循环遍历列表,然后分配 endptr = firstptr,这意味着 tempptr 将始终等于 firstptr 并且endptr 和条件 temptr!=endptr 永远不会失败

代替

firstptr=firstptr->nextptr;

利用

tempptr = tempptr->nextptr;

您也可以使用 do { } while() 语句并在开始时初始化 endptr

于 2012-12-14T09:41:06.507 回答