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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值