题目
原始地址:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { }}
描述
局部翻转一个单链表,从m到n。要求原地调整并且只能遍历一次。
分析
这个题目的思路比较好理解,首先找到第m-1个节点,然后反转第m到n个节点,最后再将前m-1个节点,反转后的第m到第n节点以及n之后的节点分别连起来即可。
解法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode dummy = new ListNode(0), prev, curr, next = null, start = dummy, end; dummy.next = head; for (int i = 0; i < m - 1; i++) { start = start.next; } end = start.next; prev = null; curr = start.next; for (int i = m; i <= n; i++) { next = curr.next; curr.next = prev; prev = curr; curr = next; } start.next = prev; end.next = next; return dummy.next; }}