gpt4 book ai didi

c++ - 测试一个简单的链表,但它坚持向后迭代

转载 作者:行者123 更新时间:2023-11-30 02:55:49 26 4
gpt4 key购买 nike

我制作了一个简单的链表,看看我是否完全理解它们,目前我正在尝试验证所有数据点是否都在正确的位置。他们不是,但我不确定为什么。我认为问题出在两个方面之一。这要么是列表构建中的错误,要么是我尝试输出数据的方式有问题。

//////////////
//linkedlist.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
namespace LinkedListMagno
{
class LinkList
{
public:
LinkList(int theData, LinkList* thePoint) : data(theData), point(thePoint){};
int getData() {return data;}
void setData(int theData) {data = theData;}
LinkList* getLink() {return point;}
void setLink(LinkList* thePoint) {point = thePoint;}
private:
int data;
LinkList* point;
};
}//LinkedListMagno
#endif



////////////
//source.cpp
#include<iostream>
#include "linkedlist.h"
using LinkedListMagno::LinkList;
using std::cin;
using std::cout;
using std::endl;

LinkList* getListPtr(int data[], int lenOfData);
//precondition: passed an array of integers and the length of the same array
//postcondition: returns a pointer to a linked list containing the integers from data[] in the given order



int main()
{
LinkList *head, *point;
int data[] = {0,1,2,3,4,5,6,7,8,9};//these numbers will go into the list in ascending order
int len = 10;

head = getListPtr(data, len);
point = head;

for(int i=0; i<len; i++)//Pretty sure the problem is here. How on earth is it iterating backwards through the list?
{
cout << point->getData();
point = point->getLink();
}

system("PAUSE");
return 0;
}

LinkList* getListPtr(int data[], int lenOfData)
{
LinkList *head, *newPoint; //two pointers. One for the head, the other to add nodes

for(int i=0; i<lenOfData; i++)
{
if(i == 0)
{
head = new LinkList(data[i], NULL);//create new linklist object using the first data point
cout << "New Node: " << data[i] << endl;
newPoint = head;//for the first node, set newPoint equal to the head
}
else if(i>0 && i<lenOfData)
{
newPoint->setLink(new LinkList(data[i], newPoint->getLink()));
cout << "New Node: " << data[i] << endl;
//newPoint = newPoint->getLink(); Derp. Forgot to add this line.
//for each item in data[], add a new node and move newPoint* to the new location
}
}

return head;
}

预期输出:

New Node: 0
New Node: 1
New Node: 2
New Node: 3
New Node: 4
New Node: 5
New Node: 6
New Node: 7
New Node: 8
New Node: 9
0123456789Press any key to continue . . .

实际输出:

New Node: 0
New Node: 1
New Node: 2
New Node: 3
New Node: 4
New Node: 5
New Node: 6
New Node: 7
New Node: 8
New Node: 9
0987654321Press any key to continue . . . (WTF?)

我不明白。它不能通过列表向后迭代,可以吗?单链表不是那样工作的。我唯一能想到的就是链接本身乱了,但是我用的方法没看出有什么问题。你怎么看?

最佳答案

通过快速浏览代码,您在 getListPtr 中添加新节点时并没有移动 newPoint 指针。所以每个新节点都直接添加到 head 之后,因为 newPoint 被初始化为 head 并保持在那里。

关于c++ - 测试一个简单的链表,但它坚持向后迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16139252/

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