【发布时间】:2021-10-11 01:12:47
【问题描述】:
只有头部元素被打印,没有元素被进一步打印。
我的猜测是createLinkedList(int n) 函数部分内的 else{.....} 内的代码似乎没有发挥作用。
代码如下:
#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;
}
【问题讨论】:
标签: c linked-list