gpt4 book ai didi

c++ - 循环单链表,添加新节点并显示

转载 作者:太空宇宙 更新时间:2023-11-04 14:11:45 26 4
gpt4 key购买 nike

我用过的编译器都无法调试它。我试图在列表的末尾添加一个新节点然后显示它,它们没有显示任何类型的错误,都给出了 send dont send error by windows,我认为这可能是内存泄漏..请帮助我

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

最佳答案

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;
}

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

代替

firstptr=firstptr->nextptr;

使用

tempptr = tempptr->nextptr;

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

关于c++ - 循环单链表,添加新节点并显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13874908/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com