//有头结点双链表
#include <malloc.h>
#include <string.h>
#include <stdio.h>
#define max 51
struct People
{
char name[max];
char ID[max];
};
typedef struct LNode {
People data; //结点的数据域
struct LNode* next; //结点的指针域(指向下一个元素)
struct LNode* previous; //结点的指针域(指向前一个元素)
} LNode, * LinkList; //LinkList为指向结构体LNode的指针类型,这里Linklist 与LNote*等价
void printPeo(People peo);//输出people
int listLength(LinkList list);//链表的长度
void intiList(LinkList& list);//双链表初始化
LNode* GetElem(LinkList& list, int i);//按位查找元素
bool InsertLNode(LinkList& list, People peo , int i);//按位插入节点
bool DelLNode(LinkList& list, int i);//按位删除节点
void main()
{
LinkList list;
intiList(list);
People peo[4] = { {"李参政" , "0418"} , { "参政" ,"0418"} , {"政" ,"0418"} ,{"李" ,"0418"} };
for (int i = 0; i < 4; i++)
InsertLNode(list, peo[i], 1);//依次插入peo[i]
LNode* l;
l = list;
for (int i = 0; i < 4; i++)
{
l = l->next;
printPeo(l->data);
}
for (int i = 0; i < 4; i++)
DelLNode(list, 1);
printf("%d\n", listLength(list));
free(list);
}
void intiList(LinkList& list)//双链表初始化
{
//申请头指针空间
list = (LNode*)malloc(sizeof(LNode));
//初始化表头
list->previous = NULL;
list->next = NULL;
}
LNode* GetElem(LinkList& list, int i)//按位查找元素
{
if (i > listLength(list))//判断i 的有效性
return NULL;
if (i == 0)//输出头节点
return list;
LNode* p = list->next;
for (int j = 0 ; j < listLength(list);i++)
{
p = p->next;
++j;
}
return p;
}
bool InsertLNode(LinkList& list, People peo, int i)//按位插入节点
{
int len = listLength(list);
if (i > len+1 || i == 0)//判断i的有效性
return false;
//申请新的节点空间并初始化
LNode* s = (LNode*)malloc(sizeof(LNode));
s->data = peo;
s->next = NULL;
s->previous = NULL;
//链表为空表,新节点插入到表头
if (i == 1 && len == 0)
{
s->previous = list;
list->next = s;
return true;
}
//链表为非空表,新节点插入到表头
if (i == 1 && len != 0)
{
s->next = list->next;
list->next->previous = s;
s->previous = list;
list->next = s;
return true;
}
//链表不空,新节点查到表尾
if (i == len +1 && len != 0)
{
LNode* temp = GetElem(list ,len);
temp->next = s;
s->previous = temp;
return true;
}
//链表非空,且不是插入到表头、表尾
LNode* temp =list->next ;
temp= GetElem(list, i-1);
s->next = temp->next;
temp->next->previous = s;
s->previous = temp;
temp->next = s;
return true;
}
bool DelLNode(LinkList& list, int i)//按位删除节点
{
int len = listLength(list);
if (i > len || len == 0) //判断i的有效行
return false;
LNode* temp = NULL;
if (len == 1)
{
temp = GetElem(list, 1);
free(temp);
list->next = NULL;
return true;
}
temp = GetElem(list, i - 1);
LNode* del;
del = temp->next;
temp->next = del->next;
del->next->previous = temp;
free(del);
return true;
}
//链表长度
int listLength(LinkList list)
{
int i = 0;
if (list->next == NULL)
return i;
while (list->next != NULL)
{
i++;
list = list->next;
}
return i;
}
//判断两个people 是否相等
bool JudgeEq(People peo1, People peo2)
{
if (strcmp(peo1.name, peo2.name) == 0 && strcmp(peo1.ID, peo2.ID) == 0)
return true;
}
void printPeo(People peo)
{
printf("name = %s\n", peo.name);
printf("ID = %s\n", peo.ID);
printf("-------------------------------\n");
}
数据结构(c语言实现)——双链表
最新推荐文章于 2023-10-22 20:24:23 发布