reorder-list

Posted qingtianBKY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了reorder-list相关的知识,希望对你有一定的参考价值。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
//思路:通过不同的首结点获取到不同的尾结点,然后拼接
public class Solution {
   public ListNode getLastNode(ListNode head)
    {
        ListNode first = head;
        ListNode fakeLast = head;
        if (head.next == null)
        {
            return head;
        }
        while (first.next != null)
        {
            fakeLast = first;
            first = first.next;
        }
        ListNode last = fakeLast.next;
        fakeLast.next = null;
        return last;
    }
 
    public void reorderList(ListNode head)
    {
       if(head==null){
            return;
        }
        // 真的首结点
        ListNode first = head;
        // 假的首结点
        ListNode fakeFirst = head;
        while (first.next != null)
        {
            ListNode last = getLastNode(first);
            fakeFirst = first.next;
            if (fakeFirst == null)
            {
                first.next = last;
                break;
            }
            else
            {
                first.next = last;
                last.next = fakeFirst;
                first = fakeFirst;
            }
 
        }
    }
}

 

以上是关于reorder-list的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode reorder-list

LeetCode——reorder-list

reorder-list——链表快慢指针逆转链表链表合并

leetcode-Sort List

143. Reorder List

微信小程序代码片段