LeetCode2.2.2(Reverse Linked List II)

来源:互联网 发布:淘宝1111和1212 编辑:程序博客网 时间:2024/06/14 09:06

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->nullptr, m = 2 and n = 4,

return 1->4->3->2->5->nullptr.

Note: Given m, n satisfy the following condition: 1  m  n  length of list.


这道题思路不难,关键是要找准边界条件

public static void solution_2_2_2(Node head,int m,int k){Node temp = head, mNode = null, kNode = null, mPre = null, h = null;for (int i = 1; i <= k; i++) {if (i == m - 1)mPre = temp;if (i == m)mNode = temp;if (i == k)kNode = temp;temp = temp.next;}// if(mPre!=null){temp = mNode;Node t = null, p = null;for (int i = m; i <= k; i++) {p = temp.next;if (t == null) {t = temp;t.next = kNode.next;} else {temp.next = t;t = temp;}if (i == k && mPre != null) {mPre.next = t;h = head;}if (i == k && mPre == null) {h = t;}temp = p;}for (Node r = h; r != null; r = r.next) {System.out.print(r.data + " ");}}


0 0
原创粉丝点击