Problem Description
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
Input
第一行输入整数的个数N;
第二行依次输入每个整数。Output
输出这组整数。
Sample Input
8 12 56 4 6 55 15 33 62
Sample Output
12 56 4 6 55 15 33 62
Hint
不得使用数组!
Source
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
int data ;
struct node *next ;
}NODE ;
NODE *creat(int n)
{
NODE *head , *p, *tail ;
head = (NODE*)malloc(sizeof(NODE)) ;
head->next = NULL;
int i ;
tail = head ;
for(i = 0 ; i< n ; i++){
p = (NODE*)malloc(sizeof(NODE)) ;
scanf("%d",&p->data) ;
p->next = NULL ;
tail -> next = p ;
tail = p ;
}
return head ;
}
void show(NODE *head)
{
NODE *p ;
p = head ->next ;
while(p){
if(p->next == NULL){
printf("%d\n",p->data) ;
}
else printf("%d ",p->data) ;
p = p->next ;
}
}
int main()
{
int n ;
NODE *head ;
scanf("%d",&n) ;
head = creat(n) ;
show(head) ;
return 0 ;
}
不使用头结点的代码
/***********************************
A - 数据结构实验之链表一:顺序建立链表
(使用无头节点建立链表)
时间 : 2021 - 5 - 5
************************************/
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
// 首先 声明 数据 结构
typedef struct node
{
int data ; // 数据域
struct node *next ; // 指针域
}Node,*LinkList; // 注: Node 代表节点,LinkList 代表链表 ,这样写有一个好处是为了 提高代码的可读性
LinkList create(int n,LinkList list){
//首先 使用 malloc 函数给 list 分配存储空间,注malloc函数返回的是一个指针,所以需要强转
list = (LinkList)malloc(sizeof(Node)) ;
// 由于 不设置头节点,所以第一个节点就可以存放数据
if(n == 0){
return NULL ;
}
else {
//首先 将头结点进行存放数据
// 本题要求要顺序 存放 ,所以要求 尾插法
list->next = NULL;
int temp ;
scanf("%d",&temp) ;
list->data =temp;
//然后后面的操作同 含有 头节点的一致
int i = 0 ;
Node *tail = (Node*)malloc(sizeof(Node)) ;// 始终在链表的最后
tail = list ;
for( ;i<n-1; i++){
Node *p = (Node*)malloc(sizeof(Node)) ;// 存放数据的节点
p->next = NULL ;
scanf("%d",&p->data) ;
tail->next = p ;
tail = p ;
}
}
return list ;
}
void show(LinkList list){
while(list){
if(list->next == NULL ){
printf("%d\n",list->data) ;
}
else{
printf("%d ",list->data) ;
}
list = list->next ;
}
}
int main(){
int n ;
scanf("%d",&n) ; // 获得键盘上的输入
LinkList list = create(n,list) ; //创建 链表
show(list) ;
return 0 ;
}