【问题描述】
对带头结点的双向链表,实现插入算法。
【输入形式】
第一行输入一个N(N大于等于1,小于1000);
第二行输入N个整数,以空格作为分隔,创建长度为N的双向链表,为双向输出方便,需保留头尾指针;
第三行输入pos和e,以空格分隔,分别表示插入位置和插入元素的值。
【输出形式】
若插入位置合法,插入成功,则输出:
第一行从头开始顺向输出双向链表中元素,用空格分隔;
第二行从尾结点开始逆向输出双向链表中元素,用空格分隔。
若插入位置不合法,例如插入位置<1或超出链表范围,则输出error
【样例输入1】
5
-4 5 2 7 0
2 100
【样例输出1】
-4 100 5 2 7 0
0 7 2 5 100 -4
【样例输入2】
5
1 2 3 4 5
6 6
【样例输出2】
1 2 3 4 5 6
6 5 4 3 2 1
【样例输入3】
5
1 2 3 4 5
8 8
【样例输出3】
error
要完成这个问题,首先我们需要知道双向链表如何表示。
双向链表的实现:
如果在线性链表的结点中增加一个指针域,用来指向结点的直接前驱,则从表中的任一结点出发,既可以向后查找结点的后继,也可以向前查找结点的前驱。整个链表包含分别指向前驱和后继的两条链,称为双向链表。双向链表的存储结构如图所示:
双向链表的存储表示描述如下:
typedef struct DuLNode
{
ElemType data;
struct DuLNode * prior;
struct DuLNode * next;
}DuLNde,* DuLinkList;
初始化如下:
DuLinkList initList()
{
DuLNode* head;
DuLNode* rear;
head=(struct DuLNode*)malloc(sizeof(struct DuLNode));
if(!head)return NULL;
rear=(struct DuLNode*)malloc(sizeof(struct DuLNode));
if(!rear)return NULL;
head->prior=NULL;
head->next=rear;
rear->prior=head;
rear->next=NULL;
return head;
}
双向链表的插入和删除操作都必须同时进行两个反向上的指针修改,操作过程比线性表复杂。插入和删除操作如下图所示:
插入代码表示:
int insertList(DuLinkList head,int pos, ElemType e)
{
if(pos<1)
{
printf("error\n");
return 0;
}
DuLNode* p=head;
int i;
for(i=1;i<pos;i++)
{
if(p->next==NULL)
{
printf("error\n");
return 0;
}
p=p->next;
}
DuLNode* pnew;
pnew=(DuLinkList)malloc(sizeof(DuLNode));
pnew->data=e;
p->next->prior=pnew;
pnew->next=p->next;
p->next=pnew;
pnew->prior=p;
return 1;
}
最后完整代码的实现及检查:
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct DuLNode
{
ElemType data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode,*DuLinkList;
//初始化
DuLinkList initList()
{
DuLNode* head;
DuLNode* rear;
head=(struct DuLNode*)malloc(sizeof(struct DuLNode));
if(!head)return NULL;
rear=(struct DuLNode*)malloc(sizeof(struct DuLNode));
if(!rear)return NULL;
head->prior=NULL;
head->next=rear;
rear->prior=head;
rear->next=NULL;
return head;
}
//插入
int insertList(DuLinkList head,int pos, ElemType e)
{
if(pos<1)
{
printf("error\n");
return 0;
}
DuLNode* p=head;
int i;
for(i=1;i<pos;i++)
{
if(p->next==NULL)
{
printf("error\n");
return 0;
}
p=p->next;
}
DuLNode* pnew;
pnew=(DuLinkList)malloc(sizeof(DuLNode));
pnew->data=e;
p->next->prior=pnew;
pnew->next=p->next;
p->next=pnew;
pnew->prior=p;
return 1;
}
void createList(DuLinkList head,int n)
{
ElemType e;
int i;
for(i=1;i<=n;i++)
{
scanf("%d",&e);
insertList(head,i,e);
}
return;
}
void printList(DuLinkList head,DuLinkList rear)
{
DuLNode* p=head;
while(p->next!=rear)
{
p=p->next;
printf("%d ",p->data);
}
return;
}
void reprintList(DuLinkList head,DuLinkList rear)
{
DuLNode* p=rear;
while(p->prior!=head)
{
p=p->prior;
printf("%d ",p->data);
}
return;
}
int main()
{
DuLinkList head,rear;
ElemType e;
int n,pos;
scanf("%d",&n);
head=initList();
rear=head->next;
createList(head,n);
scanf("%d %d",&pos,&e);
if(insertList(head,pos,e))
{
printList(head,rear);
printf("\n");
reprintList(head,rear);
}
return 0;
}
运行结果如下: