第二节、链表拓展
1.双链表
(1)双链表定义与结构
双链表能够解决单链表的单向性的缺点。双链表是指每个节点都有指向其前驱与后继的指针,可以实现双向的操作。
我们可以简单定义它的结构体为:
1 2 3 4 5
| typedef struct Node { Elemtype data; struct Node *prior,*next; }
|
(2)双链表的基本操作的实现
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include <stdio.h> #include <corecrt_malloc.h> #include <string.h>
typedef struct Node { char name[20]; struct Node* prior,* next; }*LNode;
LNode create(int n) { LNode p, head, s; p = (LNode)malloc(sizeof(Node)); p->name[0] = '\0'; p->prior = NULL; p->next = NULL; head = p; for (int i = 0; i < n; i++) { s = (LNode)malloc(sizeof(Node)); printf("请输入第%d个学生的姓名:", i + 1); scanf("%s", s->name); p->next = s; s->prior = p; s->next = NULL; p = s; } p->next = NULL; return head; }
LNode search(LNode head, char* x) { LNode p; char* y; p = head; while (p) { y = p->name; if (!strcmp(x, y)) return p; else { p = p->next; } } printf("未找到该数据。\n"); }
void del(LNode p) { p->next->prior = p->prior; p->prior->next = p->next; free(p); }
void Print(LNode head) { LNode p = head; while (p) { printf("%s\t", p->name); p = p->next; } }
int main() { LNode head; int n; printf("请输入你要初始化的节点数量:"); scanf("%d", &n); printf("\n"); head = create(n); Print(head);
}
|
2.循环单链表
(1)循环单链表的定义与结构体
循环单链表,可以想象为如下一个环形的链表:
其中,head是一个指向头结点的指针,A,B,C,D,E分别是一个节点。我们可以把它的结构题简单的定义为:
1 2 3 4 5
| typedef struct Node { int num; struct Node* next; }*LinkList;
|
(2)用头插法实现
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <stdio.h> #include <stdlib.h> #include <corecrt_malloc.h>
typedef struct Node { int num; struct Node* next; }*LinkList;
LinkList create() { LinkList head = (LinkList)malloc(sizeof(Node)); if (head == NULL) { printf("内存分配错误\n"); exit(1); } else { head->next = head; return head; } }
void Insert(LinkList head, int x) { LinkList p = head; LinkList s = (LinkList)malloc(sizeof(Node)); s->num = x; s->next = p->next; p->next = s; }
void Print(LinkList head) { LinkList p = head->next; while (p->next!= head) { printf("%d\t", p->num); p = p->next; } printf("%d \n", p->num); }
int main() { LinkList head = create(); for (int i = 1; i < 5; i++) { Insert(head, i);
} Print(head);
return 0; }
|