java 链表面试题_[算法面试题]-重新排序链表(Java)

[算法面试题]-重新排序链表(Java)

题目

给定一个简单的链表L:L0→L1→...→Ln-1→Ln,将其

重新排序为:L0→Ln→L1→Ln-1→L2→Ln-2→...

例如,给定{1,2,3,4},将其重新排序为{1,4,2,3}。您必须在原有链表上操作,而不能创建新的链表。

参考解决方案

由于该问题需要在原有链表上操作,因此我们只能更改其指针,而不能创建新链表。通过执行以下三个步骤可以解决此问题:

中间列表到两个列表的中断列表(使用快速和慢速指针)

颠倒第二个列表的顺序

将两个列表合并在一起

以下代码是带有测试的完整可运行类。

//Class definition of ListNode

class ListNode {

int val;

ListNode next;

ListNode(int x) {

val = x;

next = null;

}

}

public class ReorderList {

public static void main(String[] args) {

ListNode n1 = new ListNode(1);

ListNode n2 = new ListNode(2);

ListNode n3 = new ListNode(3);

ListNode n4 = new ListNode(4);

n1.next = n2;

n2.next = n3;

n3.next = n4;

printList(n1);

reorderList(n1);

printList(n1);

}

public static void reorderList(ListNode head) {

if (head != null && head.next != null) {

ListNode slow = head;

ListNode fast = head;

//use a fast and slow pointer to break the link to two parts.

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

//why need third/second condition?

System.out.println("pre "+slow.val + " " + fast.val);

slow = slow.next;

fast = fast.next.next;

System.out.println("after " + slow.val + " " + fast.val);

}

ListNode second = slow.next;

slow.next = null;// need to close first part

// now should have two lists: head and fast

// reverse order for second part

second = reverseOrder(second);

ListNode p1 = head;

ListNode p2 = second;

//merge two lists here

while (p2 != null) {

ListNode temp1 = p1.next;

ListNode temp2 = p2.next;

p1.next = p2;

p2.next = temp1;

p1 = temp1;

p2 = temp2;

}

}

}

public static ListNode reverseOrder(ListNode head) {

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

return head;

}

ListNode pre = head;

ListNode curr = head.next;

while (curr != null) {

ListNode temp = curr.next;

curr.next = pre;

pre = curr;

curr = temp;

}

// set head node's next

head.next = null;

return pre;

}

public static void printList(ListNode n) {

System.out.println("------");

while (n != null) {

System.out.print(n.val);

n = n.next;

}

System.out.println();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值