我正在尝试创建一个(有序)链表的(有序)链表。列表列表链接由其成员列表的第一个节点携带。我试图通过以下代码来实现此目的,但在我尝试查看列表列表中的第二个节点后,我的程序立即崩溃。
这是我尝试构建的数据结构的示意图:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct node{
int number;
struct node*next;
struct node*lsnext;
};
typedef struct node Node;
Node* insertValue(Node * list, int value);
void display(Node*);
Node* insertArr(Node * list, int value);
int main()
{
Node *globalList = NULL, *lists,*start,*save;
int nbrOfLists, listNo, nbrOfVal, valNo, val;
printf("\n Enter the number of lists:");
scanf("%d", &nbrOfLists);
if(nbrOfLists < 0)
return -1;
for(listNo = 0; listNo < nbrOfLists; listNo++)
{
printf("\n\n Enter the number of inputs to the list %d: \n ",listNo+1);
scanf("%d", &nbrOfVal);
lists = NULL;
for(valNo = 0; valNo < nbrOfVal; valNo++)
{
printf("Enter node value %d:", valNo+1);
scanf("%d", &val);
// Here we insert the value in both lists
lists= insertValue(lists, val);
globalList = insertValue(globalList, val);
}
start=lists;
if(listNo==0){
save=start;
}
start=start->lsnext;
printf("\n The list %d is: ",listNo+1);
display(lists);
}
printf("\n\n The final list is: ");
display(globalList);
printf("The first list is");
display(save);
printf("The second list is");
display(save->lsnext); // CRASHES HERE
return 0;
}
Node* insertValue(Node * list, int value)
{
Node *newNode, *m;
newNode = malloc(sizeof(Node));
newNode->number=value;
if(list == NULL)
{
newNode->next=NULL;
return newNode;
}
if(value < list->number)
{
newNode->next = list;
return newNode;
}
m = list;
while(m->next)
{
if(value < m->next->number)
break;
m = m->next;
}
newNode->next = m->next;
m->next = newNode;
return list;
}
void display(Node*nodex){
while(nodex)
{
printf("%d ->",nodex->number);
nodex=nodex->next;
}
}
最佳答案
问题是您从未分配 lsnext 节点指针。在重置开始指针之前,您需要确保将此指针设置为等于“列表”。并且您不需要以下代码行:
start=start->lsnext;
这解决了您提到的崩溃问题,但是源代码还有其他错误。通过 GDB 运行您的应用程序对于确保您的指针值是您认为在每一步中应该是的值以及源代码格式化程序来确保可读性,使您更容易判断哪些代码属于哪些 block 来说非常有值(value)。
关于c - 有序链表的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28915660/