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

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

    震惊

    震惊

编辑推荐
Reverse Linked List II Reverse a linked list from position m to n. Do it in-place and in one-
Reverse Linked List II Reverse a linked list from position m to n. Do it in-place and in one-
原题: Reverse a linked list from position m to n. Do it in-place and in one-pass. For exampl
题目概述: Reverse a singly linked list. 翻转一个单链表,如:1->2 输出 2->1;1->2-&g
206. Reverse Linked List My Submissions Question Total Accepted: 74536 Total Submissions: 200
标题: Reverse Linked List II 通过率: 26.2% 难度: 中等 Reverse a linked list from position
Given a linked list, return the node where the cycle begins. If there is no cycle, return nul
Given a linked list, return the node where the cycle begins. If there is no cycle, return nul
Given a linked list, return the node where the cycle begins. If there is no cycle, return nul
Reverse a singly linked list. 一、题目描述 翻转单链表 二、解题思路 利用两个结点指针和一个中间
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号