C 创建链表时返回空值的函数
我已经创建了一个函数,它将返回链接列表的基本地址。 它总是返回最后一个节点地址(null),而不是第一个节点C 创建链表时返回空值的函数,c,C,我已经创建了一个函数,它将返回链接列表的基本地址。 它总是返回最后一个节点地址(null),而不是第一个节点 #include<stdio.h> #include<stdlib.h> typedef struct _LinkedList { int data; struct LinkedList *nextVal; }LinkedList; //function to create a linked list LinkedList* createLL(
#include<stdio.h>
#include<stdlib.h>
typedef struct _LinkedList
{
int data;
struct LinkedList *nextVal;
}LinkedList;
//function to create a linked list
LinkedList* createLL()
{
LinkedList *ll;
ll=malloc(sizeof(LinkedList));
ll->nextVal =malloc(sizeof(LinkedList));
int i;
int count = 5;
for(i=0;i<5;i++)
{
ll->nextVal = malloc(sizeof(LinkedList));
ll->data = i;
printf("LL data value %d address val %p\n ",ll->data,ll->nextVal);
}
//last node should point to null
ll->nextVal=NULL;
printf("======================\n");
return ll;
}
int main()
{
LinkedList *basePtr;
int i;
basePtr=createLL();
for(i=0;i<5;i++)
{
printf("LL data value %d address val %p\n ",basePtr->data,basePtr->nextVal);
}
return 0;
}
#包括
#包括
类型定义结构链接列表
{
int数据;
结构链接列表*nextVal;
}链接列表;
//函数创建链接列表
LinkedList*createLL()
{
LinkedList*ll;
ll=malloc(sizeof(LinkedList));
ll->nextVal=malloc(sizeof(LinkedList));
int i;
整数计数=5;
对于(i=0;inxtval=malloc(sizeof(LinkedList));
ll->data=i;
printf(“LL数据值%d地址值%p\n”,LL->data,LL->nextVal);
}
//最后一个节点应指向null
ll->nextVal=NULL;
printf(“========================================\n”);
返回ll;
}
int main()
{
LinkedList*basePtr;
int i;
basePtr=createLL();
对于(i=0;idata,basePtr->nextVal);
}
返回0;
}
在createLL()
和main()
中,在for
的两个循环中,您不更新列表的头指针,只覆盖原始指针。(即,您没有链接列表,您有五个悬挂节点,其中四个泄漏内存)。类似这样的情况如何:
LinkedList *createLL()
{
LinkedList *head = NULL;
for (int i = 0; i < 5; i++) {
// use sizeof(*pointer) instead of sizeof(type), by the way
LinkedList *tmp = malloc(sizeof(*tmp));
tmp->next = head;
tmp->data = i;
head = tmp;
}
return head;
}
LinkedList*createLL()
{
LinkedList*head=NULL;
对于(int i=0;i<5;i++){
//顺便说一下,使用sizeof(*指针)代替sizeof(类型)
LinkedList*tmp=malloc(sizeof(*tmp));
tmp->next=头部;
tmp->data=i;
水头=tmp;
}
回流头;
}
在main()
中重复此模式,您就可以开始了。这将返回最后一个节点值,对吗?不是第一个?@user968000它将以相反的顺序构建列表,但您可以访问所有节点。