Leetcode 143 ReorderList (带头节点) java

package AlgorithmInterview;

/**
 * 对链表进行重新排序
 * Given 1->2->3->4, reorder it to 1->4->2->3.
 * Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
 * 此处为带头节点, 包含默认构造函数的链表
 */
class LNode{
    int val;
    LNode next;
}
public class ReorderListNodeB1_4 {
    public static void main(String[] args) {
        int i = 1;
        LNode head = new LNode();
        head.next = null;
        LNode temp = null;
        LNode cur = head;
        for (; i < 8; i++){
            temp = new LNode();
            temp.val = i;
            temp.next = null;
            cur.next = temp;
            cur = temp;
        }
        System.out.println("排序前: ");
        for(cur = head.next; cur != null; cur = cur.next){
            System.out.print(cur.val + " ");
        }
        reorderList(head);
        System.out.println("\n排序后: ");
        for (cur = head.next; cur != null; cur = cur.next){
            System.out.print(cur.val + " ");
        }
    }
    //找中间的结点
    public static LNode FindMiddleNode(LNode head){
        if (head == null || head.next == null) return head;
        LNode fast = head, slow = head;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    //链表的原地反转
    public static LNode Reverse(LNode head){
        if(head==null||head.next==null) return head;
        LNode p=head,q=head.next,tmp;
        p.next=null;
        while(q!=null){
            tmp=q.next;
            q.next=p;
            p=q;
            q=tmp;
        }
        return p;
    }
    //将原始链表中间结点后面的子链表部分反转后,与前半部分形成两个链表
    //对两个链表进行合并:从两个链表中各取一个结点进行合并
    public static void reorderList(LNode head){
        if (head == null || head.next == null) return ;
        LNode p = head.next;
        LNode mid = FindMiddleNode(head.next);
        LNode tail = Reverse(mid.next);
        mid.next = null;
        LNode q = tail;
        LNode cur, qtmp;
        while (p != null && q != null){
            cur = p.next;
            p.next = q;
            qtmp = q.next;
            q.next = cur;
            p = cur;
            q = qtmp;
        }
    }
}

你可能感兴趣的:(java,数据结构)