一般我们使用的是单链表,亦即只有一个指针域next指向下一个结点,但是有时候我们需要找一个结点的上一个结点,这时候就需要遍历整个链表,时间复杂度较大,所以就有了双向链表:
双向链表只是比单链表多了一个前向指针域prior,指向上一个结点:
typedef struct doublelist {
struct doublelist * prior;
int data;
struct doublelist * next;
}dobleline, *dPtr;
对双链表的插入也比较简单,进行头插法,关键是插入的时候不像单链表一样只需要将next指针进行指向就可以,还需要判断prior指针,进行指向
双向链表头插法(包含头结点):
dPtr insertLine(dPtr head, int data) {
dPtr node = (dPtr)malloc(sizeof(doublelist)); //创建新结点
node->data = data ;
node->next = node->prior = NULL;
//INSERT
node->prior = head;
node->next = head->next;
head->next = node;
if(node->next) //判断是否是第一个插入的结点
node->next->prior = node;
return head;
}
再进行正逆序打印:
void listPrint(dPtr head) {
dPtr temphead = head;
//正向打印
cout << "正序打印" << endl;
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
cout << "==============================================" << endl;
//逆向打印
cout << "逆序打印" << endl;
//移动到最后一个结点
while (temphead->next) temphead = temphead->next;
while (temphead) {
cout << temphead->data << " ";
temphead = temphead->prior; //反向打印
}
cout << endl;
}
整体代码:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef struct doublelist {
struct doublelist * prior;
int data;
struct doublelist * next;
}dobleline, *dPtr;
//头结点
dPtr initList(dPtr head) {
head = (dPtr)malloc(sizeof(dobleline));
head->prior = NULL;
head->data = 1;
head->next = NULL;
return head;
}
dPtr insertLine(dPtr head, int data) {
dPtr node = (dPtr)malloc(sizeof(doublelist));
node->data = data ;
node->next = node->prior = NULL;
//INSERT
node->prior = head;
node->next = head->next;
head->next = node;
if(node->next)
node->next->prior = node;
return head;
}
void listPrint(dPtr head) {
dPtr temphead = head;
//正向打印
cout << "正序打印" << endl;
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
cout << "==============================================" << endl;
//逆向打印
cout << "逆序打印" << endl;
while (temphead->next) temphead = temphead->next;
while (temphead) {
cout << temphead->data << " ";
temphead = temphead->prior;
}
cout << endl;
}
int main() {
dPtr head = NULL;
head = initList(head);
insertLine(head, 2);
insertLine(head, 3);
insertLine(head, 4);
insertLine(head, 5);
listPrint(head);
return 0;
}
看看打印效果: