2. 双链表
(1)实现一个双链表
双链表的实现在一定程度上与单链表相似,可参见前面的单链表的实现。
#include <stdafx.h>
#include <iostream>
using namespace std;
struct DNode
{
int data;
DNode *left;
DNode *right;
DNode(int _data=0, DNode *_left=NULL, DNode *_right=NULL):data(_data), left(_left), right(_right){}
//【注】构造函数中的参数不能为const型的,因为数据成员都是非const型的,不能将const型变量转化为非const型的
};
int main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
DNode *head = new DNode(a[0]);
DNode *p = head;//p为双链表的遍历指针
for(int i=1; i!=10; ++i)
{
DNode *newDNode = new DNode(a[i], p);
p->right = newDNode;
p = newDNode;
}
for(p=head; p!=NULL; p=p->right)
cout << p->data << " ";
cout << endl;
}
(2)双链表的删除
void deleteDNode(DNode *&head, const int item)
{
DNode *currPtr, *prevPtr;
//查找被删除结点的位置
for(prevPtr=NULL, currPtr=head; currPtr!=NULL && currPtr->data!=item; prevPtr = currPtr, currPtr=currPtr->right);
if(NULL == prevPtr)//第一种特殊情况:被删除结点在表首
{
head = head->right;
head->left = NULL;
delete currPtr;
}
else if(NULL == currPtr)//第二种特殊情况:无可删除结点
cout << "can not find " << item << endl;
else if(NULL == currPtr->right)//第三种特殊情况:被删除结点在表尾(与单链表相比较)
{
prevPtr->right = NULL;
delete currPtr;
}
else
{
prevPtr->right = currPtr->right;
currPtr->right->left = prevPtr;
delete currPtr;
}//与单链表的删除不同的是,双链表由于可以双向遍历,只需一个指针就可以完成上面的任务了
}
(3)双链表的插入
void insertDNode(DNode *&head, const int item)
{
DNode *currPtr, *prevPtr;
DNode *newDNode = new DNode(item);
//查找新结点要插入的位置
for(prevPtr=NULL, currPtr=head; currPtr!=NULL && item>currPtr->data; prevPtr=currPtr, currPtr=currPtr->right);
if(NULL == prevPtr)
{
newDNode->right = head;
head->left = newDNode;
head = newDNode;
}
else if(NULL == currPtr)
{
newDNode->left = prevPtr;
prevPtr->right = newDNode;
}
else
{
newDNode->right = currPtr;
newDNode->left = prevPtr;
prevPtr->right = newDNode;
currPtr->left = newDNode;
}
}