建链表
因为有不少朋友向我询问链表的一些事情,他们都在问链表指针啥的写起来都好麻烦的,有啥用呢。。。。。。。作为一只萌新就浅谈些我的一些感觉吧
我一开始的时候也是比较排斥链表的,因为这玩意一开始接触真的感到太麻烦了,它做到的很多东西,数组也都可以,为啥还要用这么麻烦的方式呢。。。。后来上企业课的时候,开始模拟写软件,就是一个比较简单的学生管理系统(最低级的那种),我们班的大多数同学都还没有学链表,老师就用数组来存学生信息,然后,我就发现如果用数组的话,你的信息修改会非常的麻烦,不,是特别特别的麻烦。。。
所以呢,我现在才感受到了链表无比的优越性,所以呢学好链表对于以后的软件开发的数据处理有着十分重要的作用。所以呢 ,就把那几行码码过来。。。。。。希望能帮到我的同学
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node*next;
};
struct node*creat(int n)//链表的录入
{
struct node*head,*p,*q;
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
q = head;
for(int i = 1;i<=n;i++)
{
p = (struct node*)malloc(sizeof(struct node));
scanf("%d",&p->num);
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
void show(struct node*head)//链表的输出
{
struct node*tail;
tail = head->next;
while(tail!=NULL)
{
if(tail->next==NULL)
printf("%d\n",tail->num);
else
printf("%d ",tail->num);
tail = tail->next;
}
}
int main()
{
int n;
scanf("%d",&n);
struct node*head;
head = creat(n);
show(head);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
上面的这个是正序录入的,下面的这个是逆序录入,两者差不多,就两行代码不同,我在其后做出标记
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node*next;
};
struct node*creat(int n)
{
struct node*head,*p,*q;
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
q = head;
for(int i = 1;i<=n;i++)
{
p = (struct node*)malloc(sizeof(struct node));
scanf("%d",&p->num);
head->next = p->next;//××××
head->next = p;//××××
}
return head;
}
void show(struct node*head)
{
struct node*tail;
tail = head->next;
while(tail!=NULL)
{
if(tail->next==NULL)
printf("%d\n",tail->num);
else
printf("%d ",tail->num);
tail = tail->next;
}
}
int main()
{
int n;
scanf("%d",&n);
struct node*head;
head = creat(n);
show(head);
return 0;
}