试实现带头结点的循环双链表插入操作。
函数接口定义:
Status ListInsert_DuL(DuLinkList &L, int i, ElemType e) ;
//在带头结点的双向链表L中第i个位置之前插入元素e
//i的合法值为1≤i≤表长+1
裁判测试程序样例:
#include<iostream>
using namespace std;
typedef int Status;
typedef int ElemType;
typedef struct DuLNode {
ElemType data;
struct DuLNode *prior;
struct DuLNode *next;
} DuLNode, *DuLinkList;
DuLinkList GetElemP_DuL(DuLinkList L, int i) {
int j;
DuLinkList p;
p = L->next;
j = 1;
while (j < i && p!=L) {
p = p->next;
++j;
}
if (p==L || j > i)
return NULL;
return p;
}
Status ListInsert_DuL(DuLinkList &L, int i, ElemType e) ;
void CreateDuList(DuLinkList &L,int n);//建立循环双链表,实现细节隐藏
void print(DuLinkList &L)
{
DuLinkList p;
int flag=1;
p = L->next;
while (p) {
if(flag)
cout << p->data;
else
cout << " "<< p->data;
flag=0;
p = p->next;
}
}
int main() {
int a;
ElemType e;
int n;
DuLinkList L, p;
cin >>n;
CreateDuList(L,n);
cin >> a >> e;
ListInsert_DuL(L, a, e);
print(L);
return 0;
}
/* 请在这里填写答案 */
输入格式:
输入第一行中给出1个整数n(0<n),为双链表结点数。第二行依次输入n个数。第三行输入两个数i和e,表示在第i个位置之前插入元素e
输出格式:
正序输出双链表结点值。
输入样例:
6
1 3 5 7 9 11
3 5
输出样例:
1 3 5 5 7 9 11
代码实现:
Status ListInsert_DuL(DuLinkList &L, int i, ElemType e){
int x=0;
DuLNode *p=L;
while(x<i){ //查找
p=p->next;
x++;
}
DuLNode *q;
q=(DuLNode*)malloc(sizeof(DuLNode)); //建立新节点
q->data=e; //赋值
q->prior=p->prior;//以下为插入结点操作 背记就完了
q->next=p;
p->prior->next=q;
p->prior=q;
return 0;
}