数据结构之双链表基本操作

/*
删除节点时,无须找到要删除节点的前驱节点,直接对目标节点进行删除操作。
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#define OK 1
#define ERROR 0

typedef struct Node
{
int data;
struct Node *next;
struct Node *prior;
}Node,*Lnode;

typedef struct DoubLinklist
{
Lnode Head;
Lnode Last;
int length;

}DoubLinklist,*DoubleLinklist;


DoubleLinklist Creat_DLLst()
{

DoubleLinklist L = (DoubleLinklist)malloc(sizeof(DoubLinklist));
L->Head = (Lnode)malloc(sizeof(Node));
if(!L->Head )
exit(0);
memset(L->Head ,0,sizeof(Node));

L->Last = (Lnode)malloc(sizeof(Node));
if(!L->Last )
exit(0);
memset(L->Last ,0,sizeof(Node));
L->Last->next =NULL;

L->Head ->next = L->Last ;
L->Last ->prior = L->Head;
L->length = 0;

return L;

}
/*在链表尾部追加节点*/
int Append_Node(DoubleLinklist L,int len)
{
int i;
Lnode q = L->Head;
for(i=0;i<len;++i)
{
Lnode p = (Lnode)malloc(sizeof(Node));
p->data = i;

p->prior = q;
p->next = L->Last ;
L->Last ->prior = p;
q->next = p;
L->length ++;
q = p;
}
return OK;
}

int Insert_Node(DoubleLinklist L,int i,int item)
{
int m = 1;
Lnode p ,q;
p=(Lnode)malloc(sizeof(Node));
if(!p)
exit(0);
p->data = item;
q=L->Head ->next ;
while(q!=L->Last &&m<i)
{
++m;
q=q->next ;
}
p->prior = q;
p->next = q->next ;
q->next ->prior = p;
q->next = p;

return OK;

}

int Delete_Node(DoubleLinklist L,int i,int *item)
{
int m = 0;
Lnode p = L->Head ->next ;
while(p->next !=L->Last &&m<i)
{
p=p->next ;
++m;
}
*item = p->data ;
printf("删除的元素是:");
printf("%d\n\n\n",*item);
p->prior ->next =p->next ;
p->next ->prior = p->prior ;
free(p);
return OK;

}

int Printf_data(DoubleLinklist L)
{
Lnode p =L->Head ->next ;
while(p!=L->Last )
{
printf("%d\n",p->data );
p = p->next ;
}
return OK;
}

int main()
{
int item;
DoubleLinklist L;
L= Creat_DLLst();
Append_Node( L,10);
Insert_Node(L,2,8);
Delete_Node(L,2,&item);
Printf_data(L);
return 0;
}

posted @ 2018-12-08 18:47  请叫我晓风哥哥  阅读(165)  评论(0编辑  收藏  举报