LeetCode OJ:Reverse Linked List II
2014-01-23 00:57
405 查看
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.
算法思想:
找到第m-1位置保存,将m到n位置依次next指针指向前一个元素,将第m位置元素指向n+1元素位置,m-1位置元素指向n位置元素,注意处理改变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){ ListNode *p=new ListNode(0); ListNode *q,*r,*link,*nh; p->next=head; nh=p; int count=0; while(p){ q=p->next; if(count==m-1)link=r=p; else if(count>=m&&count<=n){ p->next=r; r=p; } if(count==n){ link->next->next=q; link->next=p; } p=q; count++; } return nh->next; } };
相关文章推荐
- LeetCode OJ--Reverse Linked List II
- LeetCode OJ - Reverse Linked List II
- LeetCode OJ 92. Reverse Linked List II
- LeetCode OJ:Reverse Linked List II(反转链表II)
- LeetCode OJ - Reverse Linked List II
- LeetCode(Reverse Linked List II) 反转指定位置之间的节点
- Leetcode Reverse Linked List II
- LeetCode 92. Reverse Linked List II
- Reverse Linked List II
- LeetCode:Reverse Linked List II 解法
- leetcode-92. Reverse Linked List II(将单链表部分进行转置)
- LeetCode OJ - Linked List Cycle II
- LeetCode - Reverse Linked List II
- [leetcode 92] Reverse Linked List II
- leetCode 92.Reverse Linked List II (反转链表II) 解题思路和方法
- [leetcode]Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Leetcode139: Reverse Linked List II
- [LeetCode] Reverse Linked List II @ Python [提供自创的示意图 Figure illustration]