(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++学习之路
- 下一篇: java 的序列化和反序列化的问题