#include<stdio.h>
#include<malloc.h>
typedef int bool;
#define false 0//后面没分号;
#define true 1
typedef char Elemtype;
typedef struct Snode
{
Elemtype data;
struct Snode *prior;
struct Snode *next;
}snode;
void initlinklist(snode **p);
void destorylist(snode **p);
bool listinsert(snode *p,int i,Elemtype e);
void displist(snode *p);
int lengthlist(snode *h);
bool listempty(snode *p);
bool getlistdata(snode *p,int i,Elemtype *e);
int locate(snode *p,Elemtype e);
bool deletelist(snode *p,int i);
void initlinklist(snode **p)
{
if((*p) == NULL)
{
*p = malloc(sizeof(snode));
(*p)->prior = NULL;
(*p)->next = NULL;
}
}
void destorylist(snode **p)
{
snode *q = *p;
snode *s;
while(q)
{
s = q->next;
free(q);
q = s;
}
*p = NULL;
}
bool listinsert(snode *p,int i,Elemtype e)
{
snode *s;//定义放在最前面。
int j = 0;//当J=0是p指向头结点。保持好对应关系,让他们同增。
snode *q=p;//q负责找到第i-1个结点;
s = malloc(sizeof(snode));
s->data = e;
while(j<i-1&&q)
{
q = q->next;
j++;
}
if(q)
{
s->next = q->next;
if(q->next)//如果插入最后一个节点,则不赋值;
q->next->prior = s;
s->prior = q;
q->next = s;
return true;
}
else
return false;
}
void displist(snode *p)
{
snode *s = p->next;
while(s)
{
printf("%c\n",s->data);
s = s->next;
}
}
int lengthlist(snode *h)
{
int len = 0;
snode *s = h;
while(s->next)//这里(s->next)稍加注意
{
len++;
s = s->next;
}
return len;
}
bool listempty(snode *p)
{
return p->next == NULL;
}
bool getlistdata(snode *p,int i,Elemtype *e)
{
int j=0;
snode *s = p;
while(j<i&&s)
{
s = s->next;
j++;
}
if(s == NULL)
return false;
else
{
*e = s->data;
return true;
}
}
bool deletelist(snode *p,int i)
{
int j=0;
snode *s=p;
snode *res;
while(j<i-1&&s)
{
s = s->next;
j++;
}
if(s == NULL)
return false;
else
{
res = s->next;
if(res == NULL)
return false;
if(res->next)
res->next->prior = s;
s->next = res->next;
free(res);
return true;
}
}
int locate(snode *p,Elemtype e)
{
int i = 1;
snode *s = p->next;
while(s->data!=e&&s)
{
i++;
s=s->next;
}
return i;
}
int main(void)
{
snode *p = NULL;
Elemtype e;
initlinklist(&p);
listinsert(p,1,'a');
listinsert(p,2,'b');
listinsert(p,3,'c');
listinsert(p,4,'d');
listinsert(p,5,'e');
printf("输出双链表元素如下\n");
displist(p);
printf("输出双链表的长度%d\n",lengthlist(p));
listempty(p);
listinsert(p,4,'f');
printf("输出双链表元素如下\n");
displist(p);
getlistdata(p,3,&e);
printf("第3个字母为%c\n",e);
printf("输入你要搜寻的字母\n");
scanf("%c",&e);
printf("%c在第%d个位置\n",e,locate(p,e));
if(deletelist(p,5))
displist(p);
else
printf("dsfsf");
destorylist(&p);
return 0;
}
双链表一系列操作
最新推荐文章于 2022-05-30 18:17:29 发布