gpt4 book ai didi

c++ - 链表反向函数 OOP C++

转载 作者:行者123 更新时间:2023-11-28 05:45:14 28 4
gpt4 key购买 nike

我正在为我的链表编写反向函数,但我不知道如何将 head 指向列表中新的第一个数字。在 main 中声明 head 为 ListNode* 并通过引用传递它是行不通的,因为我还有很多其他函数不想修改。还有其他方法吗?这是我的头文件:

// Specification file for the NumberList class
#ifndef NUMBERLIST_H
#define NUMBERLIST_H

class NumberList
{
private:
// Declare a structure for the list
struct ListNode
{
double value; // The value in this node
struct ListNode *next; // To point to the next node
};

ListNode *head; // List head pointer

public:
// Constructor
NumberList()
{ head = nullptr; }

// Destructor
~NumberList();

// Linked list operations
void appendNode(double);
void insertNode(double);
void deleteNode(double);
int searchList(double);
void reverseList() const;
void displayList() const;
};
#endif

这里是反向函数。放置 head = previousNode 将不起作用:

void NumberList::reverseList() const
{
ListNode *currentNode; // points to current node
ListNode *previousNode = nullptr; // stores address of previous node
ListNode *nextNode = nullptr; // stores the address of next node
ListNode *tempNode = nullptr; //

currentNode = head;

while (currentNode != nullptr)
{
cout << "current value: " << currentNode->value << endl;
nextNode = currentNode->next;
currentNode->next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
//head = previousNode;
}

*编辑:在 main() 中添加

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

int main()
{
NumberList nList;
ifstream inFile;
double number;
double searchedNum;

inFile.open("input.txt");

if (!inFile)
{
cout << "File could not be opened!" << endl;
}
else
{
while (inFile >> number)
{
nList.appendNode(number);
}

cout << "The list after file reading:" << endl;
nList.displayList();

cout << "What number would you like to search for? ";
cin >> searchedNum;
cout << "Position: " << nList.searchList(searchedNum) << endl;

cout << "The list after reversing:" << endl;
nList.reverseList();
nList.displayList();
}



return 0;
}

最佳答案

这是一个迭代版本(我用 //Added * 标记了更改):

void NumberList::reverseList()
{
ListNode *currentNode; // points to current node
ListNode *previousNode = nullptr; // stores address of previous node
ListNode *nextNode = nullptr; // stores the address of next node

currentNode = head;
ListNode* temp; // Added*
while (currentNode != nullptr)
{
temp = currentNode->next; // Added *
nextNode = currentNode->next;
currentNode->next = previousNode;
previousNode = currentNode;
currentNode = temp; // Added *
}
}

关于c++ - 链表反向函数 OOP C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361185/

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