循环SIngly LInked LIst,添加新节点并显示它

时间:2012-12-14 08:16:47

标签: c++

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

#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();
 }

1 个答案:

答案 0 :(得分:0)

temptr = firstptr;      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循环遍历list然后你分配endptr = firstptr,这意味着tempptr将始终等于firstptr和endptr 和条件temptr!= endptr永远不会失败

而不是

  

firstptr = firstptr-&GT; nextptr;

使用

  

tempptr = tempptr-&gt; nextptr;

你也可以使用do {} while()语句并在begginng中初始化endptr