为什么不能插入到尾节点啊?
这是一个双向循环链表,要实现插入和删除的功能?能够插入节点但是不能插入尾节点?不知道该怎么改代码?#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define ERROR -1
#define NULL 0
typedef int ElemType;
typedef int Status;
typedef struct node
{
int data;
struct node *prior;
struct node *next;
}Lnode,*DuLinklist;
void creat(DuLinklist &L)
{
DuLinklist p,q;
int i;
L=(DuLinklist)malloc(sizeof(Lnode));
L->next=L;
L->prior=L;
q=L;
for(i=1;i<=5;i++)
{
p=(DuLinklist)malloc(sizeof(Lnode));
printf("input number:\n");
scanf("%d",&p->data);
p->next=L->prior;
p->prior=q;
q->next=p;
q=p;
}
}
void print(DuLinklist L)
{
DuLinklist p;
p=L->next;
while(p!=L)
{
printf("%5d",p->data);
p=p->next;
}
printf("\n");
}
Status insert(DuLinklist &L,int i,ElemType e)//不能够插入一个元素到尾节点?代码改如何修改?
{
DuLinklist p;
DuLinklist s;
p=L->next;
int j=0;
int m=5;
if(i<1)
{
return ERROR;
}
if(i<=m&&i>=1)
{
while(p&&j<i-1)
{
p=p->next;
++j;
}
s=(DuLinklist)malloc(sizeof(Lnode));
s->data=e;
s->prior=p->prior;
p->prior->next=s;
s->next=p;
p->prior=s;
}
if(i>m)
{
s=(DuLinklist)malloc(sizeof(Lnode));
s->data=e;
s->prior=L->prior;
L->prior->next=s;
s->next=L;
L->prior=s;
}
return OK;
}
Status Delete(DuLinklist &L,int i,ElemType e)
{
DuLinklist p;
int m=5;
int j=0;
p=L->next;
while(p&&j<i-1)
{
p=p->next;
++j;
}
if(i<1)
{
return ERROR;
}
if(i<=m&&i>=1)
{
e=p->data;
p->prior->next=p->next;
p->next->prior=p->prior;
free(p);
}
if(i>m)
{
e=p->data;
p->prior->next=p->next;
p->next->prior=p->prior;
free(p);
}
return OK;
}
int main(int argc, char* argv[])
{
DuLinklist L;
int i=0;
int e=0;
creat(L);
print(L);
printf("\n");
printf("input weizhi:\n");
scanf("%d",&i);
printf("input insert_number:\n");
scanf("%d",&e);
insert(L,i,e);
print(L);
printf("\n");
printf("input delete_address:\n");
scanf("%d",&i);
Delete(L,i,e);
print(L);
return 0;
}