本文主要是介绍LeetCode 92. Reverse Linked List II (链表 推荐),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Reverse a linked list from position m to n. Do it in one-pass.
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
题目链接:https://leetcode.com/problems/reverse-linked-list-ii/
题目分析:记录翻转前的节点revPre,记录翻转后的那段链表的头和尾
0ms,时间击败100%
/*** 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) {ListNode helper = new ListNode(0);helper.next = head;ListNode cur = helper, a, b, c, last, revPre;for (int i = 0; i < m - 1; i++) {cur = cur.next;}revPre = cur;a = revPre.next;b = a.next;last = a;int pos = 0;while (pos < n - m) {c = b.next;b.next = a;a = b;b = c;pos++;}revPre.next = a;last.next = b;return helper.next;}
}
这篇关于LeetCode 92. Reverse Linked List II (链表 推荐)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!