反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL
https://leetcode-cn.com/problems/reverse-linked-list-ii/
迭代
1 -> 2 -> 3 -> 4 -> 5 -> NULL
1 -> 3 -> 2 -> 4 -> 5 -> NULL
1 -> 4 -> 3 -> 2 -> 5 -> NULL
我们可以看出来,总共需要n-m步即可,第一步是将结点3放到结点1的后面,第二步将结点4放到结点1的后面。
比如刚开始,pre指向结点1,cur指向结点2,然后我们建立一个临时的结点t,指向结点3(注意我们用临时变量保存某个结点就是为了首先断开该结点和前面结点之间的联系,这可以当作一个规律记下来),
然后我们断开结点2和结点3,将结点2的next连到结点4上,也就是 cur->next = t->next,
再把结点3连到结点1的后面结点(即结点2)的前面,即 t->next = pre->next,
最后再将原来的结点1和结点2的连接断开,将结点1连到结点3,即 pre->next = t。
这样我们就完成了将结点3取出,加入结点1的后方。第二步将结点4取出,加入结点1的后方,也是同样的操作,参见代码如下:
c++
class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode *dummy = new ListNode(-1), *pre = dummy; dummy->next = head; for (int i = 0; i < m - 1; ++i) pre = pre->next; ListNode *cur = pre->next; for (int i = m; i < n; ++i) { ListNode *t = cur->next; cur->next = t->next; t->next = pre->next; pre->next = t; } return dummy->next; } };
java
class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; for(int i = 1; i < m; i++){ pre = pre.next; } head = pre.next; for(int i = m; i < n; i++){ ListNode t = head.next; head.next = t.next; t.next = pre.next; pre.next = t; } return dummy.next; } }
递归
java
class Solution { ListNode successor = null; // 后驱节点 // 反转以 head 为起点的 n 个节点,返回新的头结点 ListNode reverseN(ListNode head, int n) { if (n == 1) { // 记录第 n + 1 个节点 successor = head.next; return head; } // 以 head.next 为起点,需要反转前 n - 1 个节点 ListNode last = reverseN(head.next, n - 1); head.next.next = head; // 让反转之后的 head 节点和后面的节点连起来 head.next = successor; return last; } ListNode reverseBetween(ListNode head, int m, int n) { // base case if (m == 1) { return reverseN(head, n); } // 前进到反转的起点触发 base case head.next = reverseBetween(head.next, m - 1, n - 1); return head; } }
来源:https://www.cnblogs.com/wwj99/p/12394781.html