gpt4 book ai didi

c++ - 无法插入有序链表

转载 作者:行者123 更新时间:2023-11-30 02:03:07 25 4
gpt4 key购买 nike

我正在为我的类(class)编写一个包含三个文件的 C++ 程序。这个程序是有序链表。该程序编译但在我尝试插入时崩溃(运行程序,选择选择按回车,键入一个 int 以插入并按回车)。任何帮助将不胜感激。

驱动文件:

#include "SortedLinkedList.h"
#include <iostream>
using namespace std;


int displayMenu();
void proccessChoice(int, SortedLinkedList&);

int main()
{
SortedLinkedList sSList;
int choice = displayMenu();

do
{
if (choice != 3)
{
proccessChoice(choice, sSList);
}
} while (choice != 3);


return 0;
}

void proccessChoice(int input, SortedLinkedList& l)
{
switch(input)
{
case 1:
int num;
cout << "Please enter a int: ";
cin >> num;
l.addItem(num);
break;
case 2:
l.popFirst();
break;
}


}

int displayMenu()
{
int choice;

cout << "menu" << endl;
cout << "===========" << endl;
cout << "1. add an int" << endl;
cout << "2. Show Sorted Linked List" << endl;
cout << "3. Exit" << endl;
cin >> choice;
cin.ignore();

return choice;
}

声明文件:

struct sslNode
{
sslNode* next;
int item;
};

class SortedLinkedList
{
private:
sslNode* head;
bool isEmpty ();

public:
SortedLinkedList();
~SortedLinkedList();
void addItem(int);
int popFirst();
};

执行文件:

#include <iostream>
using namespace std;
#include "SortedLinkedList.h"

SortedLinkedList::SortedLinkedList()
{
head = NULL;
}

SortedLinkedList::~SortedLinkedList()
{
sslNode *temp, *nextLink;
nextLink = head;

while(nextLink != NULL)
{
temp = nextLink->next;
delete nextLink;
nextLink = temp;
}
}

bool SortedLinkedList::isEmpty()
{
return (head == NULL);
}

void SortedLinkedList::addItem(int itemToInsert)
{
sslNode* cur;
sslNode* prev;
sslNode* newNode = new sslNode();
newNode->item = itemToInsert;
newNode->next = NULL;

cur = head;
prev = NULL;
bool moreToSearch (cur != NULL);

while (moreToSearch) //Find insertion point
{
if (cur->item > newNode->item) // while current location has a greater value then what needs to be inserted move pointers forward.
{
prev = cur;
cur = cur->next;
moreToSearch = (cur != NULL);
}
else // if current loacation and what is to be inserted are equal or less then we have found the point of insertion
{
moreToSearch = false;
}
}

if (prev = NULL)
{
newNode->next = head->next;
head = newNode;
}
else
{
prev->next = newNode;
newNode->next = cur;
}

//Insert as only item in list
//Insert in found location
}

int SortedLinkedList::popFirst()
{
sslNode* first;
first = head->next;
head = head->next;
int item = first->item;

return item;
}

最佳答案

你的问题是你忘记了一个=

if (prev = NULL)
{
newNode->next = head->next;
head = newNode;
}
else
{
prev->next = newNode;
newNode->next = cur;
}

if(prev = NULL)

应该是

if(prev == NULL)

现在这总是错误的,因为 prev 变成 null 计算结果为 false然后它失败了

prev->next = newNode;

因为您正在取消引用空指针。

在尝试插入任何内容之前,您还需要处理 head == NULL 的情况。基本上如果 head == NULL,head = newNode;

关于c++ - 无法插入有序链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12413163/

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