双向链表的实现---数据结构学习(三)

    在单链表中,每个节点只有一个指针指向它的直接后继,访问数据时只能沿着指针向前访问。若要访问某一节点的前驱节点,只能从头开始访问。为解决这一问题而引出了双向链表的概念。双向链表中的每个节点包含两个指针(prior和next)分别指向它的前驱和后继,从一个节点出发既可以访问它的后继节点,也可访问它的前驱节点。可大大节省访问前驱节点的时间。

本文主要实现双向链表的初始化、插入、删除和输出操作。实现代码如下:

#include
using namespace std;
struct node
{
int data;
node *prior;
node *next;
};
node *head;
void init()
{
node *p, *news;
p = (node*)new node;
int x, n;
cout << "输入链表长度:";
cin >> n;
for (int i = 1; i <= n; i++)
{
news = (node*)new node;
cout << "输入第" << i << "个元素:";
cin >> x;
news->data = x;
news->prior = NULL;
news->next = NULL;
if (i == 1)
{
p = news;
head = p;
}
if (i > 1 && i < n)
{
news->prior = p;
p->next = news;
p = news;
}
if (i == n)
{
news->prior = p;
p->next = news;
news->next = NULL;
p = news;
}
}
cout << "初始化完成。" << endl;
}
void output()
{
node *p=(node*)new node;
p = head;
cout << "输出双向链表:";
do
{
cout << p->data << " ";
p = p->next;
} while (p!=NULL);
cout << endl;
}
void insert()
{
node *p, *news;
p = head;
int x, n;
cout << "输入插入位置:";
cin >> n;
cout <cin >> x;
news = (node*)new node;
news->data = x;
news->next = NULL;
news->prior = NULL;
if (n == 1)
{
news->next = head;
head->prior = news;
head = news;
}
else
{
for (int i = 1; i < n - 1; i++)
{
p = p->next;
}
news->next = p->next;
news->prior = p;
p->next = news;
p = news;
}
cout << "插入成功。" << endl;
}
void dele()
{
node *p=(node*)new node;
p = head;
node *q=(node*)new node;
int  n;
cout << "输入删除位置:";
cin >> n;
if (n == 1)
{
head = p->next;
head->prior = NULL;
free(p);
}
else
{
for (int i = 1; i < n; i++)
p = p->next;
if (p->next != NULL){
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
}
else
{
p->prior->next = NULL;
free(p);
}
}
cout << "删除成功。" << endl;
}
int main()
{
init();
output();
insert();
output();
dele();
output();
return 0;
}

你可能感兴趣的:(数据结构学习,数据结构,双向链表,链表)