/*单向链表转双向链表
* 拆分单向链表中的每一个节点,重新连接,生成双向链表
* */
# include <iostream>
using namespace std;
//辅助结构体作为链表节点
struct Node1 //单向链表节点
{
int value;
Node1* next;
};
struct Node2 //双向链表节点
{
int value;
Node2* prev;
Node2* next;
};
//单向链表构建函数(头插法)
Node1* Insert1 (int a,Node1*& head1)
{
Node1* p = NULL;
p = new Node1;
p->value = a;
if (head1 == NULL)
{
p->next = NULL;
head1 = p;
} else {
p->next = head1;
head1 = p;
}
}
//双向链表构建函数(头插法)
void Insert2 (int a,Node2*& head2,Node2*& tail)
{
Node2* p = NULL;
p = new Node2;
p->value = a;
if (head2 == NULL)
{
tail = p;
p->next = NULL;
head2 = p;
tail->prev = NULL;
} else {
p->next = head2;
head2->prev = p;
p->prev = NULL;
head2 = p;
}
}
//查看单向链表
void show1(Node1*& head1)
{
Node1*p = head1;
cout << "单向链表1 :" << endl;
while (p != NULL){
cout << p->value << " ";
p = p->next;
}
cout << endl;
}
//查看双向链表(这里从尾向前查看,验证双向链表)
void show2(Node2*& tail)
{
Node2*p = tail;
cout << "双向链表2 :" << endl;
while (p != NULL){
cout << p->value << " ";
p = p->prev;
}
cout << endl;
}
//拆分单向链表,将每一个元素依次插入双向链表
void resolve(Node1* head1,Node2*& tail)
{
Node1*
p = head1;
Node1* r = NULL; //用于保存p的上一个节点的位置,删除防止内存泄露
Node2* head2 = NULL;
Node2*
q = NULL;
while (p != NULL){
q = new Node2;
q->value = p->value;
r = p;
Insert2(p->value,head2,tail);
p = p->next;
delete r; //删除r指向的空间,直接删除p指向的空间的话p会变成野指针
}
}
int main()
{
Node1* head1 = NULL;
Insert1(3,head1);
Insert1(5,head1);
Insert1(7,head1);
Insert1(9,head1);
show1(head1);
Node2* tail = NULL;
resolve(head1,tail);
show2(tail);
return 0;
}