【每日一题】2021年12月4日-143. 重排链表

这篇博客介绍了多种方法对单链表进行重新排序,包括使用ArrayList、递归、双端队列以及找到链表中点并反转后半部分再合并的方法。通过详细代码展示了每种方法的实现细节,适合于理解链表操作和算法实践。

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

//方法1:放入ArrayList
class Solution {
    public void reorderList(ListNode head) {
        if(head == null) {
            return;
        }
        List<ListNode> list = new ArrayList<ListNode>();
        ListNode node = head;
        while(node != null) {
            list.add(node);
            node = node.next;
        }
        int i = 0, j = list.size() - 1;
        while(i < j) {
            list.get(i).next = list.get(j);
            i++;
            if(i == j) {
                break;
            }
            list.get(j).next = list.get(i);
            j--;
        }
        list.get(i).next = null;
    }
}

//方法2:递归

//方法3:双端队列

//方法4:找中点mid,后部分反转reverse,两部分合并merge
class Solution {
    public void reorderList(ListNode head) {
        if(head == null) {
            return;
        }
        //找中点
        ListNode mid = middle(head);
        ListNode l1 = head;
        ListNode l2 = mid.next;
        mid.next = null;
        l2 = reverse(l2);
        merge(l1, l2);
    }

    public ListNode middle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        //注意循环条件不是fast!=null,而是next和next.next
        while(fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public void merge(ListNode l1, ListNode l2) {
        ListNode l1_Next;
        ListNode l2_Next;
        while(l1 != null && l2 != null) {
            l1_Next = l1.next;
            l2_Next = l2.next;
            l1.next = l2;
            l1 = l1_Next;
            l2.next = l1_Next;
            l2 = l2_Next;
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值