Description:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
Note:
For example:
Given 1->2->3->4->5->NULL
, m =
2 and n = 4,
return 1->4->3->2->5->NULL
.
Solution:
Analysis and Thinking:
題目不是將整個鏈表進行反轉,而是把下標範圍爲[m,n]的節點進行反轉,因此需要把整個鏈表分成三段,分別是待反轉左段,待反轉段,待反轉右段。算法的重點在於處理帶反轉段的反轉操作以及將三段進行反轉後連接。
Steps:
1.從鏈表頭結點開始,遍歷直到待反轉段的起始位置,並用變量記錄待反轉起始點的前一個節點位置
2.從m到n開始,不斷重複進行如下步驟:當前節點的next指針指向前一節點(這裏用a->next以及PrePoint記錄),再把前一節點PrePoint更新爲當前節點,當前節點更新爲其next指針指向的節點(即a=a->next),遍歷完成後,完成反轉
3.將鏈表的3個子段進行連接,主義,需要判斷初始點是否爲head頭結點的位置以及結束點是否爲尾節點的位置。
Codes:
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n)
{
if(head==NULL)
return NULL;
ListNode *a=head;
ListNode *b=NULL;
for(int i=0;i<m-1;i++) //對第一分段進行處理
{
b=a;
a=a->next;
}
ListNode *endPoint=a;
ListNode *PrePoint=a;
for(int i=m+1;i<=n;i++)
{
ListNode *NextPoint=a->next;
a->next=PrePoint;
PrePoint=a;
a=NextPoint;
}
endPoint->next=a;
if(b)
b->next=PrePoint;
else
head=PrePoint;
return head;
}
};
Results: