题解 | 牛牛的单向链表
牛牛的单向链表
https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4
#include <stdio.h>
#include <stdlib.h>
#define N 100
struct Node
{
int data;//数据域
struct Node *next;//指针域,指向下一节点
};
struct Node* createList(int arr[],int n)
{
struct Node *head = NULL, *tail = NULL;
for(int i = 0; i < n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = arr[i];
newNode -> next = NULL;
if(head == NULL)
{
head = newNode;
tail = newNode;
}
else {
tail -> next = newNode;
tail = newNode;
}
}
return head;
}
void printList(struct Node *head)
{
struct Node *p = head;
while(p != NULL)
{
printf("%d ",p -> data);
p = p -> next;
}
}
int main()
{
int n;
scanf("%d",&n);
int arr[N];
for(int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
struct Node *head = createList(arr,n);
printList(head);
return 0;
}

