C语言 程序创建链表不工作



只打印head元素,不打印其他元素。

我的猜测是else{.....}内部的代码在createLinkedList(int n)函数部分似乎没有做它的工作。

代码如下:

#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node * next;
}*head;
void createLinkedList(int n)
{
int i;
struct Node *temp, *p;

for(i=1; i<=n; i++)
{
// First thing we do is create an ISOLATED NODE WHICH IS NOT LINKED TO ANYTHING 

temp = (struct Node *)malloc(sizeof(struct Node));
printf("Now enter your element %d of linked list: ",i);
scanf("%d",&(temp->data));
temp->next = NULL;

// ISOLATED NODE CREATED. SINCE THIS IS UNLINKED, WE MUST STORE IT'S POINTER VARIABLE TO NULL


if(head == NULL) // Meaning our Linked List is empty
head = temp; 

else // Meaning our Linked List is not empty. Has at least one element.
{
p = head;
while(p != NULL)
p = p->next;  // Accessing Last pointer of Linked List

p = temp; // THAT IOSOLATED NODE Is Hereby Connected to our final Linked LIST Element
}
printf("n");
}
}
int main() 
{
head = NULL;
printf("Enter the length of your linked list: ");
int n;
scanf("%d", &n);
printf("n");
createLinkedList(n);
return 0;
}

修改while(p != NULL) p = p->next;

while(p->next != NULL)
p = p->next; 

这将为您提供可以插入节点的最后一个指针位置。现在,p将在迭代结束时为空。

之后,您需要执行p->next = temp以便将新创建的节点添加到链表中。

我们可以跟踪链表中最后一个节点的尾指针,而不是在else块中循环。下面是修改后的代码:

void createLinkedList(int n)
{
int i;
struct Node *temp, *tail;

for(i=1; i<=n; i++)
{
// First thing we do is create an ISOLATED NODE WHICH IS NOT LINKED TO ANYTHING 

temp = (struct Node *)malloc(sizeof(struct Node));
printf("Now enter your element %d of linked list: ",i);
scanf("%d",&(temp->data));
temp->next = NULL;

// ISOLATED NODE CREATED. SINCE THIS IS UNLINKED, WE MUST STORE IT'S POINTER VARIABLE TO NULL


if(head == NULL) // Meaning our Linked List is empty
{
head = temp;
tail = temp;
}

else // Meaning our Linked List is not empty. Has at least one element.
{
tail->next = temp; // THAT IOSOLATED NODE Is Hereby Connected to our final Linked LIST Element
tail = temp;
}
printf("n");
}
}
int main() 
{
head = NULL;
printf("Enter the length of your linked list: ");
int n;
scanf("%d", &n);
printf("n");
createLinkedList(n);
return 0;
}

你的代码工作,但你失去了下一个节点的地址,当你使用while(p != NULL),所以你应该把它改为while(p->next != NULL){p=p->next;}{p->next=temp;}

最新更新