标签:
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.
相关问题是
public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode h = new ListNode(-1); h.next = head; ListNode pre = h; int cnt = 1; while(cnt<m){ pre = pre.next; cnt++; } ListNode mnode = pre.next; ListNode nnode = mnode; while(cnt<n){ nnode = nnode.next; cnt++; } ListNode end = nnode.next; reverse(pre, end); return h.next; } public void reverse(ListNode pre, ListNode end){ // B keep to being inserted after pre pre-1-2-3-end, 1= A, 2=B, 3=t ListNode A = pre.next, B = A.next; // A 定义为B前面一位, 不断的把B塞到pre后面(也就是list的第一位,然后把原来B的前面A链接到B的后面t上去 while( B!=end){ ListNode t = B.next; B.next = pre.next; pre.next = B; A.next = t; B=t; } } }
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4397689.html