一,问题描述
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

本文介绍了一种在不改变节点值的情况下,将单链表重新排序的方法。具体步骤为:先将链表从中间切分,再逆序其中一个子链表,最后合并两个子链表。附带提供了一个实现该算法的Java程序示例。
364

被折叠的 条评论
为什么被折叠?



