(LeetCode 92)Reverse Linked List II
生活随笔
收集整理的這篇文章主要介紹了
(LeetCode 92)Reverse Linked List II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
?
題目要求:
這是對反轉鏈表的一個變形,簡單的反轉鏈表實現可以參考http://www.cnblogs.com/AndyJee/p/4461502.html
反轉部分鏈表(將第m個結點到第n個結點間的元素翻轉)
注意點:
in-place原地,即不開辟額外的結點空間
one-pass一次遍歷
解題思路:
1、找到第m個結點,找到第n個結點,通過指針保存第m-1個結點和第n+1個結點;
2、將第m個結點和第n個結點間的元素反轉;
3、將1~m、m~n、n~length三部分連接起來,這里需要考慮m是否等于1,即是否為頭結點。如果是,需將head指向第n個結點;
4、返回head結點指針。
參考代碼:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* reverseBetween(ListNode* head, int m, int n) {if(head==NULL || head->next==NULL)return head;ListNode *prev=head;ListNode *curr=head;ListNode *next=head;ListNode *mPrev=NULL;ListNode *mTh=NULL;ListNode *nTh=NULL;ListNode *nNext=NULL;for(int i=1;curr!=NULL;i++){next=curr->next;if(i==m){mPrev=prev;mTh=curr;}if(i>m && i<=n)curr->next=prev;if(i==n){nTh=curr;nNext=next;}prev=curr;curr=next;}if(m==1){mTh->next=nNext;head=nTh;}else{mPrev->next=nTh;mTh->next=nNext;}return head;} };總結
以上是生活随笔為你收集整理的(LeetCode 92)Reverse Linked List II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开始我的c++学习之路
- 下一篇: 数据库中文乱码问题的解决