1.概念
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。
结构图如下所示:
2.基本操作实例
DoubleList.cpp
#include "stdafx.h" #include "DoubleList.h" #include <stdio.h> #include <malloc.h> #include <stdlib.h> DoubleList::DoubleList() { pDoubleListNode pDouList = NULL; // 创建双链表 CreateDouList(pDouList); PrintDouList(pDouList); // 打印逆序链表 PrintDouReverseList(pDouList); // 节点后插入节点 InsertNodeAfter(pDouList); PrintDouList(pDouList); // 节点前插入节点 InsertNodeBefore(pDouList); PrintDouList(pDouList); // 删除节点 DeleteNode(pDouList); PrintDouList(pDouList); // 删除链表 DeleteDouList(pDouList); PrintDouList(pDouList); system("PAUSE"); } DoubleList::~DoubleList() { } //创建双向链表 void DoubleList::CreateDouList(pDoubleListNode &head) { char x; // 定义成char型是用于输入'q'时可以退出,其实定义成int也能退出 pDoubleListNode p, s; head = (pDoubleListNode)malloc(sizeof(DoubleListNode)); head->next = NULL; head->prior = NULL; // 构造头结点p p = head; printf("\n输入双向链表的元素,每输入一个元素后按回车,输入q表示结束.\n"); fflush(stdin); //清空输入缓冲区 x = getchar(); while (x != 'q') { s = (pDoubleListNode)malloc(sizeof(DoubleListNode)); s->data = x - '0'; // 得到的是输入字符的ASCII码,减去30H就变成想要的数字 s->next = NULL; s->prior = p; p->next = s; p = s; fflush(stdin); x = getchar(); } if (x == 'q') { printf("双向链表构造完毕!\n"); } } //打印双向链表 void DoubleList::PrintDouList(pDoubleListNode &head) { pDoubleListNode p; printf("\n打印出双向链表数据为:\n"); if (!