无需遍历链表节点数据尾插

无需遍历的链表尾插法

由于课程需要运用链表的相关知识

便在中国大学慕课(https://www.icourse163.org/course/ZJU-9001)以及哔哩哔哩(https://www.bilibili.com/video/BV1sJ411E7St?share_source=copy_web

中查找了相关的视频,其中于翁恺老师课程的视频中发现了这一方法,个人觉得比较简便,于是写了出来

代码如下:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 // 用于忽略(消除)Visual Studio中的警告
 5 #pragma warning(disable:4996)
 6 
 7 typedef struct tagNode {
 8     int value;
 9     struct tagNode* next;
10 }Node;
11 
12 typedef struct {
13     Node* head;
14     Node* tail;
15 }List;
16 
17 /*
18 * 尾插法插入数据,构成链表
19 */
20 void NodeTailInsert(List* head, int number);
21 
22 int main() {
23 
24     // 定义一个链表list和数number
25     List list;
26     int number;
27 
28     // 初始化链表
29     list.head = NULL;
30     list.tail = NULL;
31 
32     do {
33         scanf("%d", &number);
34         if (number != -1) {
35             NodeTailInsert(&list, number);
36         }
37     } while (number != -1);
38 
39     return 0;
40 }
41 
42 
43 void NodeTailInsert(List* pList, int number)
44 {
45     // 为新节点申请内存
46     Node* data = (Node*)malloc(sizeof(Node));
47 
48     // 检查内存申请是否失败
49     if (data == NULL) {
50         exit(0);
51     }
52 
53     data->value = number;
54     data->next = NULL;
55 
56     // 判断tail是否为空
57     if (pList->tail != NULL) {
58         pList->tail->next = data;
59     }
60     else {
61         pList->head = data;
62     }
63 
64     // 将data的地址赋值给tail,使的tail始终指向最新的尾结点
65     pList->tail = data;
66 
67 }
68 
69 // 11 12 13 14 15 -1
70 // 测试数据
View Code

因笔者初学C语言,如有错误之处,欢迎在评论区指出

(妈耶,这排版真丑)

2022-04-20

20:11:27

posted @ 2022-04-20 20:16  一块一块儿  阅读(65)  评论(0)    收藏  举报