题解 | #牛牛的单向链表#
牛牛的单向链表
https://www.nowcoder.com/practice/95559da7e19c4241b6fa52d997a008c4
#include <stdio.h>
//定义结构体变量
typedef struct Node
{
int num;
struct Node *next;
}LinkNode;
int main(int argc, char const *argv[])
{
int n,i;
scanf("%d", &n);//获取元素个数
LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));//创建一个头链表
LinkNode *tail;
head->next = NULL;
scanf("%d", &head->num);
{
LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
scanf("%d", &p->num);
p->next = NULL;
tail->next = p;
tail = tail->next;
printf("%d ", tail->num);
tail = tail->next;
}
printf("\n");
return 0;
}
#include <stdlib.h>
typedef struct Node
{
int num;
struct Node *next;
}LinkNode;
int main(int argc, char const *argv[])
{
int n,i;
scanf("%d", &n);//获取元素个数
LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));//创建一个头链表
LinkNode *tail;
head->next = NULL;
scanf("%d", &head->num);
tail = head;
//通过循环创建链表
for (i = 0; i < n-1; ++i){
LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
scanf("%d", &p->num);
p->next = NULL;
tail->next = p;
tail = tail->next;
}
//将tail指针指向head,方便后续的遍历
tail = head;
//遍历链表的数据
while(tail!=NULL){printf("%d ", tail->num);
tail = tail->next;
}
printf("\n");
return 0;
}