欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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);
}

结果2020-10-29

相关标签: 基础学习