LeetCode 143 Reorder List

14 篇文章 0 订阅

一,问题描述

1,给一个单链表L: L0->L1->…..->Ln-1->Ln 。
重新排序成L: L0->Ln->L1->Ln-1->L2-Ln-2.
值得注意的是,您必须在不改变结点值的情况下执行此操作的。

2, 解题思路如下:
首先先把单链表从中间切开,分为左右两个子链表。
然后,对右子链表进行逆序。
最后,把两个左右子链表进行合并起来,就可以得到最终的结果。

二, AC了的程序(java)

import java.util.*;
class ListNode{
    int val;
    ListNode next;
    ListNode(int x)
    {
        val=x;
    }
}

public class Test2{

    public void reorderList(ListNode head)
    {
        if(head==null||head.next==null)
        {
            return;
        }

        ListNode first=head;
        ListNode second=first.next;

        while(second!=null&&second.next!=null)
        {
            first=first.next;
            second=second.next.next;
        }

        ListNode third=first.next; //此时拆分成两个子单链表,第一个链表是head,第二个是third链表
        first.next=null;

         //然后对第二个链表进行逆序 third单链表

        ListNode tempnode=null;
        while(third!=null)
        {
            ListNode node=third.next;
            third.next=tempnode;
            tempnode=third;
            third=node;
        }

        //tempnode就是逆序third后的单链表

        first=head;
        second=tempnode;

        //接下来就是合并head和tempnode两个子单链表
        while(first!=null)
        {
            ListNode node1=first.next;
            first.next=second;
            first=second;
            second=node1;
        }

        //首先把单链表平均分成两个子单链表
    }

    public static void main(String []args)
    {
        Test2 test=new Test2();
        ListNode l1=new ListNode(1);
        ListNode l2=new ListNode(2);
        ListNode l3=new ListNode(3);
        ListNode l4=new ListNode(4);
        ListNode l5=new ListNode(5);
        ListNode l6=new ListNode(6);
        ListNode l7=new ListNode(7);

        l1.next=l2;
        l2.next=l3;
        l3.next=l4;
        l4.next=l5;
        l5.next=l6;
        l6.next=l7;

        test.reorderList(l1);
    }

}

运行结果:

1 7 2 6 3 5 4

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值