当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

Reverse Linked List II

发表于: 2015-07-16   作者:hcx2013   来源:转载   浏览:
摘要: 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 

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

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

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

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
    	if (head==null || head.next==null) {
        	return head;
        }
    	ListNode tmp = new ListNode(-1);
    	tmp.next = head;
    	ListNode pre = tmp;
        ListNode node1 = null;
        ListNode node2 = null;
    	for (int i = 0; i < n; i++) {
    		if (i < m-1) {
    			pre = pre.next;
    		} else if (i == m-1) {
    			node1 = pre.next;
    			node2 = node1.next;
    		} else {
    			node1.next = node2.next;
    			node2.next = pre.next;
    			pre.next = node2;
    			node2 = node1.next;
    		}
    	}
    	return tmp.next;
    }
}

 

Reverse Linked List II

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号