我是靠谱客的博主 兴奋树叶,这篇文章主要介绍单链表 尾插法 C语言,现在分享给大家,希望可以做个参考。

注意用malloc开辟空间用的是node*,而其对应的访问也是用"->"

复制代码
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
48
49
50
51
52
53
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> using namespace std; struct node{ //节点 int data; node* le; }; struct chain{ //链表 node* root; //存储了链表的开头元素 }; node* gettail(chain ll){ //尾插法 寻找链尾 node* temp=(node*)malloc(sizeof(node)); temp=ll.root; while(temp->le!=NULL){ temp=temp->le; } return temp; } int main() { //单链表建立 int n; //节点个数 chain ll; //声明一个链表 ll.root->le=NULL; scanf("%d",&n); //输入节点个数 for(int i=0;i<n;i++){ //依次建立连接 node* tempnode=(node*)malloc(sizeof(node)); node* tail=(node*)malloc(sizeof(node)); int temp; scanf("%d",&temp); tail=gettail(ll); //寻找尾部保存于tail中 tempnode->data=temp; tail->le=tempnode; tempnode->le=NULL; } //链表遍历 node* temp=ll.root->le; while(temp!=NULL) { printf("%d->",temp->data); temp=temp->le; } return 0; }

输入

输出

例题

13个人围成一圈,序号为1-13,依次报数1,2,3,每次数到3的人退出圈子。然后旁边的下一个人又从1开始报数,循环往复,直到所有人都退出

输出退出的序号,用链表实现。

使用循环单链表:

复制代码
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
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; struct node{ int data; node* next; }; int main() { //链表建立 node* root=(node*)malloc(sizeof(node)); node* temp=root; for(int i=1;i<=13;i++){ node* temp1=(node*)malloc(sizeof(node)); temp->next=temp1; temp1->data=i; temp=temp1; } temp->next=root->next; //进行输出 temp=root; while(1){ for(int i=0;i<2;i++){ //找到链表中第二个元素即可,便于删除第三个元素 temp=temp->next; } if(temp->next==temp) //只剩最后一个人,直接输出并且中断循环 { printf("%d ",temp->data); break; } else printf("%d ",temp->next->data); temp->next=temp->next->next; } return 0; }

输出:

最后

以上就是兴奋树叶最近收集整理的关于单链表 尾插法 C语言的全部内容,更多相关单链表内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部