双向链表及其基本操作

#include<stdio.h>
#include<stdlib.h>
typedef struct Line{
struct Line* prior;
int data;
struct Line* next;
}line;
line* initLine(line* head,int n)
{
head=(line*)malloc(sizeof(line));//没有头结点的双向链表
head->prior=NULL;
head->data=1;
head->next=NULL;
line* list=head;
for(int i=2;i<=n;i++)
{
line* body=(line*)malloc(sizeof(line));
body->data=i;
body->prior=list;//指向直接前驱
body->next=NULL;
list->next=body;//直接前驱链接新节点
list=list->next;
}
return head;
}
void display(line* head)
{
line* list=head;
while(list!=NULL)
{
printf("%d “,list->data);
list=list->next;
}
printf(”\n");
}
line* insertLine(line* head,int data,int index)
{
line* temp=(line*)malloc(sizeof(line));
temp->data=data;
temp->next=NULL;
temp->prior=NULL;
//分情况讨论插入位置
if(index1)
{
temp->next=head;
head->prior=temp;
head=temp;
}
else{
line* p=head;
for(int i=2;i<index;i++)
{
p=p->next;
}//找到插入位置的直接前驱
if(p->next!=NULL)//插入尾巴
{
temp->next=p->next;
p->next->prior=temp;//完成后继节点的链接
}
temp->prior=p;
p->next=temp;//完成前驱节点的链接
}
return head;
}
line* delLink(line* head,int data)
{
line* temp=head;
while(temp!=NULL)
{
if(temp->data
data)
{
if(temp==head)
{
temp->next->prior=NULL;
head=temp->next;
}
else
{
if(temp->next!=NULL)
{
temp->next->prior=temp->prior;
}
temp->prior->next=temp->next;
}
free(temp);//!!!
return head;//没有对head变量进行改变也能正常指向表头???错,必须像我这么写,否则删除头结点返回会出错

	}
	temp=temp->next;
	
}//找到删除的节点

printf("链表中无该数据\n");

return head;
}

int selectLine(line* head,int elem)
{
line* temp=head;
int count=1;
while(temp!=NULL)
{
if(temp->dataelem)
{
return count;
}
temp=temp->next;
count++;
}
return -1;
}
line* updateLine(line* head,int oldData,int newData)
{
line* temp=head;
while(temp)
{
if(temp->data
oldData)
{
temp->data=newData;
printf(“修改成功\n”);
return head;
}
temp=temp->next;
}
printf(“找不到%d\n”,oldData);
return head;
}

int main()
{
int n;
scanf("%d",&n);
//创建n个节点的双链表
line* head=NULL;
head=initLine(head,n);
display(head);
head=insertLine(head,0,1);
display(head);
head=delLink(head,0);
display(head);

int index=selectLine(head,3);
if(index==-1)
{
	printf("链表中无该元素\n");
}
else
{
	printf("该元素在链表中的第%d个节点\n",index);
}

updateLine(head,3,5);
display(head);
printf("链表中的第三个节点的直接前驱是:%d\n",head->next->next->next->prior->data);

return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_33508523/article/details/88067864