题目:
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 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 {
ListNode nextNode = null;
public ListNode reverse(ListNode head, int n) {
if (n == 1) {
nextNode = head.next;
return head;
}
ListNode last = reverse(head.next, n - 1);
head.next.next = head;
head.next = nextNode;
return last;
}
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == 1) {
return reverse(head, n);
}
head.next = reverseBetween(head.next, m - 1, n - 1);
return head;
}
}
分析二:
迭代:这个方法就是多用指针,疯狂指,考虑好边界条件。
代码:
/**
* 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 head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy.next;
while (m > 1) {
first = second;
second = second.next;
m--;
n--;
}
ListNode con = first;
ListNode tail = second;
ListNode third = null;
while (n > 0) {
third = second.next;
second.next = first;
first = second;
second = third;
n--;
}
if (con != null) {
con.next = first;
} else {
dummy.next = first;
}
tail.next = second;
return dummy.next;
}
}