算法:重排链表

一、题目

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

二、思路

1)使用快慢指针找到中位点,将链表拆分成两个,然后倒转第二个链表,然后合并两个链表

2)使用双端队列

三、代码

1)

public void reorderList(ListNode head) {

        ListNode res = head;

        if (head == null || head.next == null) {

            return;

        }

        ListNode slow = head;

        ListNode fast = head;

        while (fast != null && fast.next != null) {

            slow = slow.next;

            fast = fast.next.next;

        }

 

        ListNode reverse = slow.next;

        slow.next = null;

        

        ListNode pre = null;

        ListNode cur = reverse;

 

        while (cur != null) {

            ListNode next = cur.next;

            cur.next = pre;

            pre = cur;

            cur = next;

        }

 

        reverse = pre;

 

        ListNode cur1 = head;

        ListNode cur2 = reverse;

 

        while (cur1 != null && cur2 != null) {

            ListNode next1 = cur1.next;

            ListNode next2 = cur2.next;

 

            cur2.next = next1;

            cur1.next =cur2;

 

            cur1 = next1;

            cur2 = next2;

        }

  

    }

2)

public void reorderList(ListNode head) {        

        LinkedList<ListNode> queue = new LinkedList<>();

 

        ListNode cur = head;

 

        while (cur != null) {

            queue.addLast(cur);

            cur = cur.next;

        }

 

        while (!queue.isEmpty()) {

            if (cur == null) {

                cur = queue.pollFirst();

            } else {

                cur.next = queue.pollFirst();

                cur = cur.next;

            }

 

            cur.next = queue.pollLast();

            cur = cur.next;

        }

 

        if (cur != null) {

            cur.next = null;

        }

    }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值