递归解决方案,用于显示线性链表数组



我正在研究一种递归解决方案来显示整个线性链表数组。这不是家庭作业,而是在准备考试,我来了。

我目前有一些分段错误,但我不知道为什么。我有一种感觉,我在这个代码的指针比较部分遇到了问题。 似乎正在发生的事情是我越界了,例如, 我有 4 个列表

List1 - 1 2 3 4 5
List2 - 5 4 3 2 1
List3 - 1 3 2 4 5
List4 - 2 4 3 1 5

我的函数将显示:

1 2 3 4 5
5 4 3 2 1
1 3 2 4 5
2 4 3 1 5
size is: 4

我会在之后显示所有列表和 seg 错误,但是,我不确定原因是什么,我唯一合理的怀疑是指向我检查指针比较的代码部分。我不经常在堆栈溢出上发帖,所以,如果我有任何格式问题,请相应地指导我。

//simple struct with int data
struct node
{
int data; 
node* next;
}
//table class has:
//array of linear linked lists
//size of array
class table
{
public:
/*
assume constructors and destructors are properly implemented
*/
void display();
void displayArr(node** head);
void traverse(node* head);
private:
void traverseLLL(node* head);
void displayArr(node** head);
node** head;
int size;
}
//wrapper
void table::display()
{
displayArr(head);
}
//takes in array of pointer
void table::displayArr(node** head)
{
//if no array
if(!head) return;
if(*head == head[size-1]) //pointer comparison, check bounds
{
//enter block, on last index
cout << "size is: " << size << endl;
traverse(*head); //do this
return; //get out
}
else //not on last index
{
traverse(*head); //display
++head; //increment index
displayArr(head); //recursive call
}
//traverse to the end of a LLL and displays it
void table::traverse(node* head) 
{
if(!head) return;
cout << head->data << endl;
traverse(head->next);
}

问题head[size-1].您应该记住,head指针在递归期间已移动。

您可以使用headindisplayArr以外的其他名称,以避免覆盖记录列表真正头部的类成员head

好吧,将成员head重命名为_head并将head[size-1]更改为_head[size-1]似乎更容易

最新更新