算法:重排链表

一、题目

给定一个单链表 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;

        }

    }

发布了43 篇原创文章 · 获赞 0 · 访问量 3885

猜你喜欢

转载自blog.csdn.net/zhangdx001/article/details/105363419