数据结构 - 链表
序言
- 之所以会开始写这个系列的博客, 是为了准备数据结构的考试, 顺便测试一下自己对数据结构到底掌握的怎样。
链表
- 在学C语言的过程中, 我们接触了数组, 并且使用次数非常之多, 所以我们对于数组的理解应该是不错的
- 数组的优点就在于它支持随机访问, 即可以用下标来访问、 存取元素, 缺点呢, 就是插入和删除非常麻烦, 为了方便插入、 删除元素, 在此引进链表这种数据结构
实现
- 链表是用结构体来实现的
1 struct Node { 2 int data; 3 Node *next; 4 }
- 上面这个结构体就是链表的结点, 单个的结构体变量可以认为是链表的一个链节
- 链表有个好处就是, 如果我们知道了一个链表的头结点, 就可以顺藤摸瓜, 访问到所有的结点, 而且带头结点的链表的操作会很简单, 所以我只介绍带头结点的方法
操作
- 对于链表而言, 无非就是创建, 插入, 删除, 输出
代码
- 下面给出代码
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 struct Node { 5 int data; 6 Node *next; 7 Node(int d, Node *nxt = nullptr):data(d), next(nxt){} 8 }; 9 10 ///创建链表, 并插入dat中的前n个元素 11 Node* Create(int n, int dat[]) { 12 Node *head = new Node(-1); 13 Node *temp = head; 14 15 for (int i = 0; i < n; i++) { 16 temp -> next = new Node(dat[i]); 17 temp = temp -> next; 18 } 19 return head; 20 } 21 22 ///在链表head的pos位置插入元素dat 23 ///pos大于链表长度, 则在链表尾插入 24 void Insert(Node *head, int pos, int dat) { 25 Node *temp = head; 26 27 while (temp -> next && --pos) temp = temp -> next; 28 29 temp -> next = new Node(dat, temp -> next); 30 } 31 32 ///删除链表head中所有值为dat的链节 33 ///将continue改为break可以只删除一个 34 void Delete(Node *head, int dat) { 35 Node *temp = head; 36 37 while (temp -> next) { 38 if (temp -> next -> data == dat) { 39 temp -> next = temp -> next -> next; 40 continue; 41 } 42 temp = temp -> next; 43 } 44 } 45 46 ///输出链表 47 ///如果链表只有一个头结点, 说明链表为空 48 ///注意一下输出格式 49 void Print(Node *head) { 50 Node *temp = head -> next; 51 52 if (temp == nullptr) printf("This Linklist is empty!\n"); 53 else { 54 while (temp -> next) { 55 printf("%d ", temp -> data); 56 temp = temp -> next; 57 } 58 printf("%d\n", temp -> data); 59 } 60 } 61 62 int main () { 63 int a[10] = {1, 2, 3, 3, 5, 6, 7, 8, 9, 10}; 64 Node *head = Create(10, a); Print(head); 65 Insert(head, 12, 11); Print(head); 66 Delete(head, 3); Print(head); 67 return 0; 68 }
小结
稍微总结一下, 在需要执行较多的插入删除操作时, 使用链表会比使用数组快一点, 这时可以优先使用链表
但是在刷oj上的题的时候, 当然是怎么简单怎么用, 即使题面已经明确的写了要用链表, 但是使用数组会更简单的话, 当然是用数组了
举个例子, 题目要求使用链表来写归并排序, 但是归并排序显然是用数组来的简单, 这时候当然是用数组了, 如果是在期末考试, 我建议先把链表的元素都提取出来, 排好序之后在用新的数组创建一个新链表