Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
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.
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
链表翻转题,找到第一个需要翻转的地方以及它的前一个节点,然后每往后面走一个,都有头插法插入。注意在插入的时候可能出现当m = n的时候,当前节点的next被赋给了自己而产生了一个环出来,对于这种情况根据不同的实现方式可以用不同的方法排除掉。最后注意m和n的大小关系别写反了。
public ListNode reverseBetween(ListNode head, int m, int n) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode station = dummy, temp1 = head; int cnt = m; while(cnt > 1) { // find the first element to reverse temp1 = temp1.next; station = station.next; cnt--; } n = n - m; ListNode temp2 = temp1.next; while(n > 0) { temp1.next = temp2.next; temp2.next = station.next; station.next = temp2; temp2 = temp1.next; n--; } return dummy.next; }
没有评论:
发表评论