1. Title
Reverse Linked List II
2. Http address
https://leetcode.com/problems/reverse-linked-list-ii/
3. The question
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
.
4. My code(AC)
1 // Accepted 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 4 ListNode frontDump = new ListNode(-1); 5 ListNode middleDump = new ListNode(-1); 6 ListNode lastDump = new ListNode(-1); 7 ListNode frontTail = frontDump; 8 ListNode middleTail = null; 9 ListNode tmp = null; 10 int len = 1; 11 frontDump.next = head; 12 ListNode p = head; 13 14 while( p != null && len < m) 15 { 16 frontTail = p; 17 p = p.next; 18 len++; 19 } 20 frontTail.next = null; 21 22 middleDump.next = p; 23 middleTail = p; 24 while( p != null && len <= n) 25 { 26 tmp = p.next; 27 p.next = middleDump.next; 28 middleDump.next = p; 29 p = tmp; 30 len++; 31 } 32 33 lastDump.next = p; 34 35 if( m == 1) 36 { 37 middleTail.next = lastDump.next; 38 return middleDump.next; 39 } 40 if( middleDump.next != null) 41 { 42 frontTail.next = middleDump.next; 43 middleTail.next = lastDump.next; 44 }else{ 45 frontTail.next = lastDump.next; 46 } 47 return frontDump.next; 48 }