天天看點

C++連結清單反轉C++連結清單反轉

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

結果

C++連結清單反轉C++連結清單反轉