标签:
题目:
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.
1 public ListNode reverseBetween(ListNode head, int m, int n) { 2 if(head == null) return null; 3 ListNode dummy = new ListNode(0); 4 dummy.next = head; 5 ListNode pre = dummy; 6 ListNode start = head; 7 8 for (int i = 1; i < m; i++) { 9 start = start.next; 10 pre = pre.next; 11 } 12 ListNode end = start; 13 ListNode then = start.next; 14 ListNode temp = then; 15 for (int j = 0; j < n - m; j++) { 16 temp = then.next; 17 then.next = start; 18 start = then; 19 then = temp; 20 } 21 pre.next = start; 22 end.next = then; 23 return dummy.next; 24 }
感觉写的挺丑的。。。
标签:
原文地址:http://www.cnblogs.com/gonuts/p/4418880.html