为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?

Why is it that, when I try to search for data that is beyond the first data entry in my double linked list, the program crashes?

本文关键字:数据 程序 崩溃 搜索 链表 为什么 第一个      更新时间:2023-10-16

对于我的作业,我应该创建一个双链表,并在它旁边有搜索、插入和删除功能。在开发搜索功能时,我遇到了一个错误,如果有人使用无法与链表中任何内容匹配的键进行搜索,程序将崩溃 - 打印链表第一个数据所在的内存地址。但是,除此之外,我还遇到了另一个错误,如果我要搜索第一个数据条目之外的任何数据,程序将崩溃 - 打印第一个条目的内存地址。

这些问题源于这样一个事实,即我的搜索函数没有正确迭代整个列表,但只能毫无问题地读取第一个条目。因此,如果我尝试访问超出第一个条目的任何数据,整个程序都会崩溃。我知道这最终是问题所在,但我对我做了什么导致了它以及我应该如何解决它感到困惑。

标题.h:

#pragma once
#ifndef Header_H
#define Header_H
#include "stdafx.h"
#include<iostream>
#include <string>
template<typename T>
struct Node {
T record;
Node<T> *next;
Node<T> *prev;
Node() {
next = NULL;
prev = NULL;
}
};

template<class T> 
class datax {
Node<T> *top;
Node<T> *bot;
public:
datax() {
top = NULL;
bot = NULL;
}
~datax() {}
//Searches the list that has a requested key word
void find();
//Inserts into the list a requested word
void insert();
//Searches the list for a requested key word and pops it out
void Delete();
void show();
private:
};
template<typename T>
void datax<T>::show() {
Node<T> *temp = top;
while (temp != NULL) {
cout << temp->record << "";
temp = temp->next;
}
}
template<typename T>
void datax<T>::Delete() {
T get;
Node<T>*ser = top;
cin >> get;
while (ser != NULL && ser->record != get) {
ser = ser->next;
}
if (ser != NULL && ser->record == get) {
cout << "Removing data from " << ser << endl;
ser->next->prev = ser->prev;
delete ser;
}
else {
cout << "Data not found" << endl;
}
}
template<typename T> 
void datax<T>::insert() {
T val;
Node<T> *ptr = new Node<T>;
cin >> val;
ptr->record = val;
ptr->next = NULL;
if (bot != NULL) {
bot->next = ptr;
ptr->prev = bot;
}
if (top == NULL) {
top = ptr;
}
bot = ptr;
}
template<typename T>
void datax<T>::find() {
T get;
Node<T>*ptr= top;
cin >> get;
if (ptr == NULL) {
cout << "Data not found" << endl;
}
else {
while (top != NULL && ptr->record != get) {
top->next = ptr;
}
if (ptr != NULL && ptr->record == get) {
cout << "Found: " << ptr << endl;
}
else {
cout << "Data not found" << endl;
}
}
}
#endif // !Header_H

主要:

// LinkedList.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include <string>
#include"Header.h"
using namespace std;
int main()
{
int take;
datax<int> m;
while (true) {
cout << "nn1. Insertnn2.Findnn3.Delete" << endl;
cin >> take;
switch (take) {
case 1:
m.insert();
m.show();
break;
case 2:
m.find();
break;
case 3:
m.Delete();
m.show();
break;
default:
cout << "Error" << endl;
}
}
return 0;
}

看看你的搜索循环:

while (top != NULL && ptr->record != get) {
top->next = ptr;
}

现在,你的条件是你将继续循环,直到topNULLptr->record是你要找的。但是在你的环形身体里,top会改变吗?ptr会改变吗??不!

换句话说,如果你第一次不退出这个循环,你永远不会

您可能打算让它看起来像:

while (ptr != NULL && ptr->record != get) {
ptr = ptr->next;
}

或者,如果您感觉很花哨并想要一个单行(IMO 仍然可读(:

for(ptr = top; ptr && ptr->record != get; ptr = ptr->next) { }
相关文章: