reorder-list

来源:互联网 发布:人工智能战机 编辑:程序博客网 时间:2024/06/13 23:18

题目描述:

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.


本题的想法就是先将列表平分成两份,后一份逆序,然后再将两段拼接在一起,逆序可用头插法实现。

代码实现:
package leetcoder;class ListNode2 {int val;ListNode2 next;ListNode2(int x) {val = x;next = null;}}public class ReorderList { public static void reorderList(ListNode2 head) { //链表为空或只有一个结点,直接返回 if(head == null || head.next == null) return; //把链表从中间分成两段 ListNode2 fast = head.next; ListNode2 slow = head; while(fast!=null && fast.next != null){ fast = fast.next.next; slow = slow.next; } ListNode2 p = slow.next;//P指向第二段链表的开头 slow.next = null; //使用头插法将第二段链表翻转 ListNode2 pPre = null;//pPre始终指向链表的开始节点 ListNode2 pSuf = p.next;//pSuf指向待插入的结点 while(p != null){ pSuf = p.next; p.next = pPre; pPre = p; p = pSuf; } //合并两个单链表 ListNode2 l1 = head; ListNode2 l2 = pPre; while(l1 != null && l2 != null){ ListNode2 l1Next = l1.next; ListNode2 l2Next = l2.next; l1.next = l2; l2.next = l1Next; l1 = l1Next; l2 = l2Next; } } public static void main(String[] args) {ListNode2 n1 = new ListNode2(1);ListNode2 n2 = new ListNode2(2);ListNode2 n3 = new ListNode2(3);ListNode2 n4 = new ListNode2(4);n1.next = n2;n2.next = n3;n3.next = n4;n4.next = null;reorderList(n1);ListNode2 p = n1;while(p != null){System.out.println(p.val);p = p.next;}}}




0 0
原创粉丝点击