題目
思路
參考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;
}