码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Reverse Linked List II

时间:2015-04-10 01:20:15      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

题目地址:https://leetcode.com/problems/reverse-linked-list-ii/

解题思路:

1.找到需要翻转的开始节点,从开始节点其依次进行翻转,注意过程中要维护三个节点,curr,curr.next,curr.next.next

2.如果开始翻转节点为1,则返回翻转后链表的头,否则返回原始链表的头

题目解答:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head == null){
            return null;
        }
        
        ListNode curr = head;
        ListNode firstTail = null;
        for(int i = 1;i<m;i++){
            firstTail = curr;
            curr = curr.next;
        }
        ListNode partTail = curr;
        ListNode next1 = curr.next;
        ListNode next2 = null;
        
        if(next1 != null){
            next2 = next1.next;
        }else{
            return head;
        }
        
        for(int i = m;i<n;i++){
            next1.next = curr;
            
            curr = next1;
            next1 = next2;
            if(next1 != null){
                next2 = next1.next;
            }else{
                break;
            }
        }
        
        partTail.next = next1;
        if(firstTail != null){
            firstTail.next = curr;
            return head;
        }else{
            return curr;
        }

    }
}

 

Leetcode Reverse Linked List II

标签:

原文地址:http://www.cnblogs.com/xiongyuesen/p/4413209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!