2020-10-29
程序员文章站
2022-05-29 09:57:20
...
C++链表反转
声明链表
typedef struct MyList
{
MyList * next;
int num;
}MyList;
创建链表
void craetList(MyList *head)//创建链表
{
MyList *p1 = new MyList;
p1->num = 1;
MyList *p2 = new MyList;
p2->num = 2;
MyList *p3 = new MyList;
p3->num = 3;
MyList *p4 = new MyList;
p4->num = 4;
MyList *p5 = new MyList;
p5->num = 5;
p1->next =p2;
p2->next =p3;
p3->next =p4;
p4->next =p5;
p5->next =NULL;
head->next = p1;
}
打印链表
void printfList(MyList *head)
{
MyList *temp =head->next;
while(temp!=NULL)
{
printf("%d\n",temp->num);//打印单链表
temp = temp->next;
}
system("pause");
}
反转链表
MyList* revrse(MyList * head)
{
MyList* p1 = head->next;
MyList* p2 = head->next->next;
MyList* temp = NULL;
while (p1->next != NULL)
{
p1->next =temp;
temp = p1;
p1 =p2;
p2 = p2->next;
}
p1->next = temp;
head->next =p1;
return head;
}
main函数
void main()
{
MyList *head = new MyList;
craetList(head); //单链表初始化
printfList(head);
revrse(head);//反转单链表
printfList(head);
}
结果
上一篇: MFC对话框绘制灰度直方图
下一篇: 了解芋圆甜品的做法大全,制作出好吃的甜品