双向链表与单链表相比,各个节点多了一个指向前一个节点的指针,即一个节点有一个指向前驱的指针和指向后继的指针。本文将主要介绍双向链表的基本操作,包括正向遍历链表,反向遍历链表,查找链表中的元素,节点的插入,节点的删除等操作。
双向链表结构
/* 双向链表节点结构 */
struct Node
{
int data;
Node * next, Node * pre;
Node() { data = 0; next = nullptr; pre = nullptr; }
};
/* 定义头节点 */
Node * header = new Node;
/* 定义尾节点 */
Node * tail = new Node;
tail = header;
正向遍历链表
void TraverseLinkList(Node * header)
{
if(!header->next)
return;
Node * temp = header->next;
while (temp)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
反向遍历链表
双向链表有尾节点,所以直接从尾节点从后向前遍历即可
void reverseLinkList(Node * tail)
{
Node * temp = tail;
while (temp)
{
cout << temp->data << " ";
temp = temp->pre;
}
cout << endl;
}
查找元素
Node * Findelement(Node * header, int val)
{
if(!header->next)
return;
Node * temp = header->next;
while(temp)
{
if(temp->data == val)
return temp;
temp = temp->next;
}
return NULL;
}
插入元素
插入元素有多种情况,首先看在链表末尾插入元素
void append(Node* tail, int val)
{
Node* node = new Node;
node->data = val;
tail->next = node;
node->pre = tail;
tail = node;
}
头部插入
void pushfront(Node* header, int val)
{
Node* node = new Node;
node->data = val;
header->next = node;
node->pre = header;
}
其他位置插入
void insert(Node* header, int k, int val)
{
Node* node = new Node;
node->data = val;
if(k==0) //头部插入
{
pushfront(header,val);
return;
}
int count = 1;
Node* temp = header->next;
while(temp)
{
if(count == k)
{
node->next = temp->next;
node->pre = temp;
temp->next->pre = node;
temp->next = node;
}
count++;
}
}
删除元素
void erase(Node* header, int val)
{
if(!header->next)
return;
Node* temp = header->next;
while(temp)
{
if(val == temp->data)
{
Node* tpre = temp->pre;
temp->pre->next = temp->next;
temp->next->pre = tpre;
delete temp;
temp = NULL;
}
}
}