leetcode-92-反转链表 II

描述

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

  

解法

public class TestUtil {
    public static void main(String[] args) {
        Struct s1 = new Struct();
        s1.setValue(1);
        Struct s2 = new Struct();
        s2.setValue(2);
        Struct s3 = new Struct();
        s3.setValue(3);
        Struct s4 = new Struct();
        s4.setValue(4);
        Struct s5 = new Struct();
        s5.setValue(5);

        s1.setNext(s2);
        s2.setNext(s3);
        s3.setNext(s4);
        s4.setNext(s5);
        s5.next = null;

        Struct rs = rotateLink(s1, 2, 4);
        Struct head = rs;
        String string = "";
        while (rs != null) {
            string += rs == head ? rs.getValue() : "->" + rs.getValue();
            rs = rs.next;
        }

        System.out.println(string);


    }

    public static Struct rotateLink(Struct head, int m, int n) {
        Struct pre = new Struct();
        pre.next = head;

        Struct mPreNode = pre;
        Struct mNode = null;
        Struct nNode = null;
        Struct nNext = null;

        n -= m;
        while (--m != 0) {
            mPreNode = mPreNode.next;
        }

        mNode = mPreNode.next;

        nNode = mNode.next;
        while (--n != 0) {
            nNode = nNode.next;
        }
        nNext = nNode.next;


        Struct nextNode = nNext;

        while (mNode != nextNode) {
            Struct next = mNode.next;
            mNode.next = nNext;
            nNext = mNode;
            mNode = next;
        }

        mPreNode.next = nNext;

        return pre.next;
    }
}



class Struct {
    int value;
    Struct next;

    public void setValue(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setNext(Struct next) {
        this.next = next;
    }

    public Struct getNext() {
        return next;
    }
}

  

参考:

猜你喜欢

转载自www.cnblogs.com/wangsong412/p/12013077.html