92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.
---
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(head==null || head.next == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode prev = dummy; ListNode cur=dummy; int k=m-1; while(k>0){ cur=cur.next; k--; } prev=cur; cur=cur.next; k=n-m; while(cur.next!=null && k>0){ ListNode right =cur.next; // keep the right next cur.next=right.next; right.next=prev.next; prev.next=right; k--; } return dummy.next; } }
浙公网安备 33010602011771号