gpt4 book ai didi

c++ - 结构体、链表、删除整个链表

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

如何删除链表中的所有对象,在struct中实现?在我的删除功能 (loeschen) 之后显示漫画数字,我不知道我的指针在哪里。

struct domino {
int data1;
int data2;
domino *next;


};

int readSteine (){ //Reading from numbers from file
FILE *file;


if((file=fopen("datei.dat", "r") )==NULL) { /
std::cout<<"File cant be open"<<std::endl;
return 0;
}else {
int beginning;
int temp;
fscanf(file, "%d", &beginning);

for(int i=0; i<beginning; i++) {
domino *domino1= new domino;
//if(i>0) temp2->next=domino1;
fscanf(file, "%i", &temp);
domino1->data1=temp;
fscanf(file, "%i", &temp);
domino1->data2=temp;
printf("[%d:%d]", domino1->data1, domino1->data2);
domino1->next=0;
}
}return 0;
}

列表删除函数:

void deletelist (domino *head) {
domino* tmp;
while(head != 0) {
tmp=head->next;
delete head;
head=tmp;
}

}


int main() {
domino *pHead=NULL;
domino s;
readSteine();
deletelist(pHead);
std::cout<<s.data1<<"...."<<s.data2<<std::endl;

return 0;
}

最佳答案

下面是一个清除方法的例子。思路是遍历链表,逐一删除节点。

Node *pDel = _pHead;

/* Traverse the list and delete the node one by one from the head */
while (pDel != NULL) {
/* take out the head node */
_pHead = _pHead->_pNext;
delete pDel;
/* update the head node */
pDel = _pHead;
}
/* Reset the head and tail node */
_pTail = _pHead = NULL;

关于c++ - 结构体、链表、删除整个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30743109/

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