#include <stdio.h>
#include <stdlib.h>
int a[5]={1,2,3,4,5};
//链表结构体
typedef struct Node
{
int data;
struct Node *pre;
struct Node *next;
}Node,*Pnode;
//创建链表
Pnode Creat_list(void)
{
Pnode head,tail;
head=(Pnode)malloc(sizeof(Node));
head->next=NULL;
head->next=NULL;
head->data=a[0];
//建立游指针
tail=head;
for(int i=1;i<5;i++)
{
Pnode body=(Pnode)malloc(sizeof(Node));
body->data=a[i];
body->next=NULL;
body->pre=NULL;
body->pre=tail;
tail->next=body;
//将游指针指向最后一个节点
tail=tail->next;
}
return head;
}
//双链表反转
Pnode reverse_list(Pnode phead)
{
Pnode pnode=phead,prie=NULL;
while(pnode)
{
Pnode pnext=pnode->next;//首先保存pnode的下一节点保存到pnext,否则会失去下一节点的指向
pnode->next=prie;//指向前一节点,当pnode为头结点时,pre指向为空
pnode->pre=pnext;//指向下一个节点,当pnode为空时,pre指针为空
prie=pnode;//反转完成,后移pre指针
pnode=pnext;//后移pnode指针
}
return prie;
}
//遍历双向链表
void display_list(Pnode phead)
{
Pnode temp;
temp=phead;
while(temp)
{
if(temp->next==NULL)
{
printf("%d\n",temp->data);
}
else
{
printf("%d <-> ",temp->data);
}
temp=temp->next;
}
}
int main(void)
{
Pnode list=NULL,tail=NULL;
//正序输出
list=Creat_list();
display_list(list);
//逆序输出
tail=reverse_list(list);
display_list(tail);
system("pause");
return 0;
}
双向链表的反转
最新推荐文章于 2023-04-27 19:58:35 发布