一、双向链表的定义
双向链表也是链表的一种,它每个数据结点中都有两个结点,分别指向其直接前驱和直接后继。所以我们从双向链表的任意一个结点开始都可以很方便的访问其前驱元素和后继元素。
二、双向链表的存储结构
双向链表也是采用的链式存储结构,它与单链表的区别就是每个数据结点中多了一个指向前驱元素的指针域 ,它的存储结构如下图:
当双向链表只有一个结点的时候它的存储结构如下:
三、双向链表的实现与操作
因为在双向链表中,我们可以通过任意一个结点访问到其前驱元素和后继元素,时间复杂度为O(1),所以双向链表是十分方便的,我们通常构建链表也会选择去构建双向链表。
接下来看一下双向链表的实现与操作:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> typedef struct DOUBLE_LIST { int data; struct DOUBLE_LIST *prev; struct DOUBLE_LIST *next; }double_list; double_list *createlist() //创建有n个元素的双向链表 并输入元素 { double_list *head, *p, *q; int n,x; head = (double_list *)malloc(sizeof(double_list)); head->prev = head; head->next = head; p = head; printf("输入要创建双向链表的元素的个数:\n"); scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d", &x); q = (double_list *)malloc(sizeof(double_list)); q->data = x; p->next = q; head->prev = q; q->prev = p; q->next = head; p = q; } return head; } //遍历并且输出这些元素 void printlist(double_list *head) { double_list *p; p = head; p = p->next; while(p!=head) { printf("%d ", p->data); p = p->next; } printf("\n"); } //得到现在双向链表中的元素的个数 int lengthlist(double_list *head) { double_list *p; p = head; p = p->next; int coun = 0; while(p!=head) { coun++; p = p->next; } return coun; } //在第i个元素之前插入数据data void insertlist_f(double_list *head, int i, int data) { double_list *p = head, *q; p = p->next; i--; while(i--) p = p->next; q = (double_list *)malloc(sizeof(double_list)); q->data = data; (p->prev)->next = q; q->prev = p->prev; q->next = p; p->prev = q; } //删除第i个位置的元素 void deletelist_i(double_list *head, int i) { double_list *p = head; p = p->next; i--; while(i--) p = p->next; (p->prev)->next = p->next; (p->next)->prev = p->prev; free(p); } //删除值为x的元素 void deletelist_x(double_list *head, int x) { double_list *p = head, *q; p = p->next; while(p!=head) if(p->data == x) { q = p->next; (p->prev)->next = p->next; (p->next)->prev = p->prev; free(p); p = q; } else p = p->next; } //对双向链表进行排序 void sortlist(double_list *head) //升序 { double_list *p = head, *q, *t; p = p->next; for(;p!=head;p=p->next) for(t = p->next;t!=head;t=t->next) { if(p->data > t->data) { int a = p->data; p->data = t->data; t->data = a; } } } int main() { double_list *head; head = createlist(); deletelist_x(head, 2); //sortlist(head); printlist(head); insertlist_f(head, 2, 2); printlist(head); return 0; }
原文地址:http://blog.csdn.net/fk5431/article/details/45072935