翻转链表 II

来源:互联网 发布:淘宝商城铂金会员 编辑:程序博客网 时间:2024/06/08 03:34

要求:翻转链表中第m个节点到第n个节点的部分

注意事项:m,n满足1 ≤ m ≤ n ≤ 链表长度


  • Java代码:
/** * Definition for ListNode * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    /*     * @param head: ListNode head is the head of the linked list      * @param m: An integer     * @param n: An integer     * @return: The head of the reversed ListNode     */    public ListNode reverseBetween(ListNode head, int m, int n) {        //翻转代码所需要的变量        ListNode now = head;        ListNode pre = null;        ListNode fot = null;        //记录开始翻转节点的前一个节点(即m-1位置的节点)        ListNode pNodeM = null;        int sum = 1;        //从头结点开始翻转需要特殊处理        if(m == 1){            pNodeM = head;        }        while(now != null){            pre = now.next;            if(sum == m-1){                pNodeM = now;            }            if(sum> m && sum <= n){                now.next = fot;            }            fot = now;            now = pre;            if(sum == n){                //从头结点翻转特殊处理部分                if(m==1){                    //pre为弄完节点后一个节点                    pNodeM.next = pre;                    //fot为翻转节点链表中的头结点                    head = fot;                }else{                    //将翻转后的链表与原链表链接到一起                    pNodeM.next.next = pre;                    pNodeM.next = fot;                }            }                       sum++;        }        return head;    }}
  • 题源链接:http://www.lintcode.com/zh-cn/problem/reverse-linked-list-ii/#