题目内容
Reverse a linked list from position m to n. Do it in one-pass.
Example:
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
分析过程
- 题目归类:
链表,递归方式链表 - 题目分析:
本题目的是控制链表的部分反转,我采用的方法是修改了递归链表反转算法 - 边界分析:
- 空值分析
- 循环边界分析
- 方法分析:
- 数据结构分析
- 状态机
- 状态转移方程
- 最优解
- 测试用例构建
代码实现
递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null)
return null;
int l = n-m;
ListNode node = new ListNode(0);
node.next = head;
ListNode tmp =node;
while(m>1){
node = node.next;
m--;
}
node.next=reverse(node.next,l);
return tmp.next;
}
public ListNode reverse(ListNode head, int i){
if(i == 0||head==null||head.next==null){
return head;
}
ListNode tmp = reverse(head.next,i-1);
ListNode y = head.next.next;
head.next.next = head;
head.next = y;
return tmp;
}
}