单链表的实质是一个结点的序列,建立单链表实质上就是逐个生成每一个结点,并把结点插入链表的过程,只不过需要插入的不是一个结点,而是多个结点而已,多个结点结点的插入方式是相同的,可以借助循环过程来实现。
单链表的建立有两种方式,一种是顺序建链表,一种是逆序建链表。
顺序建链表:
题目描述
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
输入
第一行输入整数的个数N;
第二行依次输入每个整数。
输出
输出这组整数。
示例输入
8
12 56 4 6 55 15 33 62
示例输出
12 56 4 6 55 15 33 62
#include<stdlib.h>
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *create(int n)//顺序建链表
{
struct node *head,*tail,*p;
int i;
head=(struct node *)malloc(sizeof(struct node));//申请头结点
head->next=NULL;
tail=head;//头尾指针指向同一个结点
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));//申请新结点
scanf("%d",&p->data);//输入结点的数据域
p->next=NULL;//结点的指针域为空
tail->next=p;//将新结点插入链表尾部
tail=p;//让链表的尾结点指向新结点
}
return (head);
};
void print(struct node *head)//输出链表中的数据
{
struct node *p;
p=head->next;
while(p!=NULL)
{
printf("%d",p->data);
if(p->next!=NULL)
printf(" ");
p=p->next;//p指向下一个结点
}
printf("\n");
}
int main()
{
int n;
struct node *head;
scanf("%d",&n);
head=create(n);//建立链表
print(head);//输出链表
return 0;
}
逆序建链表:
题目描述
输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。
输入
第一行输入整数N;;
第二行依次输入N个整数,逆序建立单链表。
输出
依次输出单链表所存放的数据。
示例输入
10
11 3 5 27 9 12 43 16 84 22
示例输出
22 84 16 43 12 9 27 5 3 11
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *create(int n)
{
struct node *head,*p;
int i;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&p->data);
p=(struct node *)malloc(sizeof(struct node));
p->next=head->next;
head->next=p;
}
return (head);
};
void print(struct node *head)
{
struct node *p;
p=head->next;
while(p!=NULL)
{
printf("%d",p->data);
if(p->next!=NULL)
printf(" ");
p=p->next;
}
printf("\n");
}
int main()
{
int n;
struct node *head;
scanf("%d",&n);
head=create(n);
print(head);
return 0;
}