leetcode24之兩兩交換鏈表中的節點

這個題有點意思,可以用遞歸的思想來解決,也可以用三指針法解決

方法一

#include <iostream>
using namespace std;

struct ListNode
{
	int val;
	ListNode* next;
	ListNode(int x):val(x),next(NULL) {}
};

ListNode* swapPairs(ListNode* head)
{
	if(head==NULL||head->next==NULL) return head;
	
	ListNode* begin=new ListNode(-1);
	begin->next=head;
	
	ListNode *first=begin,*second=first->next,*third=begin->next->next;//注意,這裏只有first是不動的 
	
	
	
	second->next=third->next;
	first->next=third;
	third->next=second;
	while(first->next->next->next&&first->next->next->next->next)//保證移動兩位之後,second和third都不爲空 
	{
		first=first->next->next;
		second=first->next;//second和third的賦值方式要注意 
		third=first->next->next;
		second->next=third->next;
		first->next=third;
		third->next=second;
	}
	
	
	
	
	return begin->next;
	
}

int main()
{
	ListNode* m1=new ListNode(1);
	ListNode* m2=new ListNode(2);
	ListNode* m3=new ListNode(3);
	ListNode* m4=new ListNode(4);
	m1->next=m2;
	m2->next=m3;
	m3->next=m4;
//	ListNode* Try=m1;
//	while(Try)
//	{
//		cout<<Try->val<<" ";
//		Try=Try->next;
//	}
	ListNode* ans=swapPairs(m1);
	while(ans)
	{
		cout<<ans->val<<" ";
		ans=ans->next;
	}
	cout<<endl;
	
	cout<<"ok"<<endl;
	return 0;
}

方法2

#include <iostream>
using namespace std;

struct ListNode
{
	int val;
	ListNode* next;
	ListNode(int x):val(x),next(NULL) {}
};

ListNode* swapPairs(ListNode* head)
{
	if(head==NULL||head->next==NULL)//這裏的順序非常重要,因爲是逐步判斷的 
	{
		return head;
	}
	ListNode *temp=head->next;
	head->next=swapPairs(temp->next);
	temp->next=head;//切斷,交換 
	return temp;
}

int main()
{
	ListNode* m1=new ListNode(1);
	ListNode* m2=new ListNode(2);
	ListNode* m3=new ListNode(3);
	ListNode* m4=new ListNode(4);
	m1->next=m2;
	m2->next=m3;
	m3->next=m4;
//	ListNode* Try=m1;
//	while(Try)
//	{
//		cout<<Try->val<<" ";
//		Try=Try->next;
//	}
	ListNode* ans=swapPairs(m1);
	while(ans)
	{
		cout<<ans->val<<" ";
		ans=ans->next;
	}
	cout<<endl;
	
	cout<<"ok"<<endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章