1. 程式人生 > >資料結構之雙鏈表基本操作

資料結構之雙鏈表基本操作

/*
刪除節點時,無須找到要刪除節點的前驅節點,直接對目標節點進行刪除操作。
*/
#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;
}