java 重排链表

牛客题目链接

1. 题目考点

  1. 找链表中间节点的两种方式
  2. 翻转链表的两种方式

2. 考点解析

  1. 原地构造两个链表 list1 和 list2,list2 采用头插法翻转原链表
public ListNode reorderList(ListNode head) {
    ListNode l1 = new ListNode(0);
    ListNode l2 = new ListNode(0);
    ListNode r1 = l1, r2 = l2, p = head;
    r1.next = head;
    int len = getLen(head);
    int mid = len >> 1;
    while (mid != 0) {
        mid --;
        r1 = p;
        p = p.next;
    }
    r1.next = null;
    
    // 头插法建立 l2
    while (p != null) {
        ListNode temp = p.next;
        p.next = l2.next;
        l2.next = p;
        p = temp;
    }
     
    ListNode dummy = new ListNode(0);
    ListNode r = dummy;
    r1 = l1.next;
    r2 = l2.next;
    
    // 合并两个链表
    while (r1 != null && r2 != null) {
        r.next = r1;
        r1 = r1.next;
        r = r.next;
         
        r.next = r2;
        r2 = r2.next;
        r = r.next;
    }
     
    if (r1 != null) r.next = r1;
    if (r2 != null) r.next = r2;
     
    return dummy.next;
}
 
public int getLen(ListNode node) {
    int i = 0;
    while (node != null) {
        i++;
        node = node.next;
    }
    return i;
}
  1. 采用快慢指针划分链表为 list1 和 list2,list2 原地翻转,原地插入合并 list1 和 list2
public void reorderList(ListNode head) {
    if(head == null || head.next == null)
        return ;
    //快慢指针,找到中间节点
    ListNode fast = head;
    ListNode slow = head;
    while(fast != null && fast.next != null){
        slow = slow.next;
        fast = fast.next.next;
    }
    ListNode mid = slow;
   // 第二个链表 p
    ListNode p = mid.next;
    // 第一个链表断链
    mid.next = null;
   
    //翻转 p 链表
    ListNode pre = null;
    while(p != null){
        ListNode temp = p.next;
        p.next = pre;
        pre = p;
        p = temp;
    }
   
    ListNode p1 = head, p2 = pre;
    // 技巧:原地插入合并
    while(p1 != null && p2!=null){
        ListNode next1 = p1.next;
        ListNode next2 = p2.next;
        p1.next = p2;
        p2.next = next1;
        p1 = next1;
        p2 = next2;
    }
    return ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值