双向链表简介
我们知道,单链表(singly linked list)只有一个指向直接后继的指针来表示结点间的逻辑关系,可以方便地查找下一个结点,但是找前驱结点就非常困难。这时,我们就需要用上双向链表(doubly linked list)来解决这个问题。
结构体构建
第一个动作和单链表类似,我们使用结构体来定义出这种数据类型。代码:
typedef struct DLinkNode{
int data;
struct DLinkNode *prev;
struct DLinkNode *next;
}DLNode,*DLNodePtr;
DLNodePtr head;//定义一个全局的头指针
创建结点
为了便于后续操作,我们写一个创建结点的函数。在之后需要创建结点的操作中直接调用此函数,减少代码的重复性。代码:
DLNodePtr GetNewNode(int x){
DLNodePtr newNode = (DLNodePtr)malloc(sizeof(DLNodePtr));
newNode->data = x;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
头插法插入结点
//头插法插入节点
void InsertAtHead(int x){
DLNodePtr temp = GetNewNode(x);
//1.链表为空,则将head设置为新节点的地址
if(head==NULL){
head = temp;
return ;
}
//2.链表不为空,在头部插入
head->prev = temp;
temp->next = head;
head = temp;
}
正反向打印链表
//正向打印
void Print(){
DLNodePtr p = head;
printf("正向输出:"