首页 > 编程语言 > 详细

[LeetCode] 92. Reverse Linked List II Java

时间:2017-12-07 10:10:20      阅读:195      评论:0      收藏:0      [点我收藏+]

题目:

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.

题意及分析:反转链表从m到n的节点,其中1 ≤ m ≤ n ≤ length of list。主要是要用一个preNode记录当前点前一个点和nextNode记录当前点后一个点,这样就可以将当前点的next指针指向preNode,然后将preNode = node, node = nextNode,继续交换后面的点即可。注意的是m==1,即从第一个点开始翻转时有一点不同。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(m==n) return head;
        ListNode startNode = head; //记录m-1的点
        ListNode preNode = head;        //记录当前点的前一个点
        ListNode nextNode = head; //记录当前点的下一个点
        ListNode node = head;
        int index = 1;
        if(m==1){       //第一个点开始翻转
            while(index <= n){
//                node = node.next;
                nextNode = node.next;       //记录下一个点
                if(index !=1){      //不是第一个点就交换指针
                    node.next = preNode;
                    preNode = node;
                }
                node = nextNode;
                index++;
            }
            startNode.next = node;
            return preNode;
        }else{      //后面点开始翻转
            ListNode temp = null;
            while(index <=n){
                if(index == m-1) {      //记录翻转点前一个点
                    startNode = node;
                    temp = node.next;
                }
                nextNode = node.next;       //记录下一个点
                if(index !=1 && index > m){      //不是第一个点就交换指针
                    node.next = preNode;
                }
                preNode = node;
                node = nextNode;
                index++;
            }
            startNode.next = preNode;
            temp.next = node;
            return head;
        }
    }
}

 

[LeetCode] 92. Reverse Linked List II Java

原文:http://www.cnblogs.com/271934Liao/p/7997568.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!