单链表的创建及遍历 题目链接
需要权限
读入n值及n个整数,建立单链表并遍历输出。
输入格式:
读入n及n个整数。
输出格式:
输出n个整数,以空格分隔(最后一个数的后面没有空格)。
输入样例:
在这里给出一组输入。例如:
2
10 5
输出样例:
在这里给出相应的输出。例如:
10 5
思路分析 :当指针指向下一结点为 NULL 时做好特殊输出即可
#include <stdio.h>
#include <malloc.h>
struct node {
int num;
struct node *next;
};
struct node *creatList(int n)
{
struct node *p, *head;
struct node *node = (struct node*)malloc(sizeof(struct node));
scanf("%d", &node->num); node->next = NULL;
n -= 1; p = head = node;
for (int i = 0; i < n; i++)
{
struct node *node = (struct node*)malloc(sizeof(struct node));
scanf("%d", &node->num); node->next = NULL;
p->next = node;
p = p->next;
}
return head;
}
int main()
{
int n;
struct node *p;
scanf("%d", &n);
if (n <= 0) return 0;
struct node *head=creatList(n);
for (p = head; p->next != NULL; p = p->next)
printf("%d ",p->num);
printf("%d",p->num);
return 0;
}