双链表的增删改查
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct DNode
{
ElemType data;
struct DNode *prior;
struct DNode *next;
}DNode,*DLinkList;
DLinkList Dlist_head_insert(DLinkList &DL)
{
int x; DNode* s;
DL = (DLinkList)malloc(sizeof(DNode));
DL->prior = NULL;
DL->next = NULL;
scanf("%d", &x);
while (x != 9999)
{
s = (DNode*)malloc(sizeof(DNode));
s->data = x;
s->next = DL->next;
if (DL->next!=NULL)
{
DL->next->prior = s;
}
DL->next = s;
s->prior = DL;
scanf("%d",&x);
}
return DL;
}
void PrintDList(DLinkList DL) {
DL = DL->next;
while (DL!=NULL)
{
printf("%3d",DL->data);
DL = DL->next;
}
}
void PrintDLlistRear(DLinkList DL)
{
int length = 0;
DNode *r = NULL;
DL = DL->next;
while (DL != NULL) {
r = DL;
DL = DL->next;
length++;
}
for (int i = 0; i < length; i++)
{
printf("%3d",r->data);
r = r->prior;
}
printf("\n");
}
DLinkList Dlist_tail_insert(DLinkList &DL)
{
int x;
DL = (DLinkList)malloc(sizeof(DNode));
DNode *r,*s;
DL->prior = NULL;
r = DL;
scanf("%d", &x);
while (x!=9999)
{
s = (DNode*)malloc(sizeof(DNode));
s->data = x;
r->next = s;
s->prior = r;
r = s;
scanf("%d",&x);
}
r->next = NULL;
return DL;
}
DNode* GetElem(DLinkList DL, int i)
{
int j = 1;
DNode* p = DL->next;
if (i==0)
{
return DL;
}
if (i<1)
{
return NULL;
}
while (p&&j<i)
{
p = p->next;
j++;
}
return p;
}
bool DListFrontInsert(DLinkList DL, int i, ElemType e)
{
DLinkList p = GetElem(DL, i - 1);
if (p==NULL)
{
return false;
}
DNode *s = (DNode*)malloc(sizeof(DNode));
s->data = e;
s->next = p->next;
p->next->prior = s;
s->prior = p;
p->next = s;
return true;
}
bool DListDelet(DLinkList DL,int i)
{
DNode *p = GetElem(DL, i - 1);
if (p==NULL)
{
return false;
}
DNode *q = p->next;
if (q==NULL)
{
return false;
}
p->next = q->next;
if (q->next!=NULL)
{
q->next->prior = p;
}
free(q);
return true;
}
int main()
{
DLinkList DL;
DLinkList search;
Dlist_tail_insert(DL);
PrintDList(DL);
search = GetElem(DL, 2);
if (search)
{
printf("\n按序号查找成功!\n");
printf("%3d\n",search->data);
}
else
{
printf("按序号查找失败\n");
}
DListFrontInsert(DL, 3, 99);
PrintDList(DL);
DListDelet(DL, 2);
PrintDList(DL);
return 0;
}