【LeetCode】92.反轉鏈表2

題目

92 反轉鏈表

思路

參考LeetCode的官方解析,迭代法完成,注意反轉之後,首尾的連接,此處是反轉鏈表2的難點

代碼

#include<iostream>
#include<vector>
using namespace std;
//鏈表定義
struct ListNode {
	int val;
	ListNode* next;
	ListNode(int x) : val(x), next(NULL) {}
	ListNode() {}
};
class Solution {
public:
	ListNode* reverseBetween(ListNode* head, int m, int n) {
		//鏈表爲空
		if (head==NULL)
		{
			return head;
		}
		//尋找開始結點位置
		ListNode* prev=NULL;//指向當前結點的前繼
		ListNode* curr = head;//當前結點
		while (m>1)
		{
			prev = curr;
			curr= curr->next;
			m--;
			n--;
		}
		//鏈表開始反轉
		ListNode* con = prev;//反轉鏈表的頭結點
		ListNode* tail = curr;//反轉鏈表的尾
		while (n>0)
		{
			ListNode* nextTemp = curr->next;//當前結點的下一個結點
			curr->next = prev;//當前結點指向其前繼
			prev = curr;//前繼改爲當前結點
			curr = nextTemp;//移到當前結點爲下一個結點
			n--;
		}
		//利用con,tail修復連接
		//設置頭
		if (con==NULL)//頭結點爲prev
		{
			head=prev;
		}
		else//不爲空
		{
			con->next = prev;
		}
		//設置尾
		tail->next = curr;
		return head;
	}
};
//創建結點
ListNode* Create(vector<int> ivec)
{
	ListNode* head=new ListNode;
	head->next = NULL;
	ListNode* p = head;
	for (int i = 0; i < ivec.size(); i++)
	{
		ListNode* q = new ListNode(ivec[i]);
		q->next = NULL;
		p->next = q;
		p = q;
	}
	return head;
}
//輸出鏈表
void PrintList(ListNode* head)
{
	while (head!=NULL)
	{
		cout << head->val << " ";
		head = head->next;
	}

}
int main()
{
	vector<int> ivec(5);
	for (int i = 0; i < ivec.size(); i++)
	{
		cin >> ivec[i];
	}
	ListNode* head = Create(ivec);
	PrintList(head->next);
	cout << endl;
	Solution s;
	PrintList(s.reverseBetween(head->next, 2, 4));
	return 0;
}
發佈了99 篇原創文章 · 獲贊 19 · 訪問量 8200
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章