题目描述
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.
代码
第一种:
三步走:
1.找到中间节点;
2.反转后半部分的节点(即中间节点之后的所有节点);
3.将两部分节点合并
代码:
public reorderList(ListNode head){if(head==null)return head;ListNode slow=head;ListNode fast=head;while(fast.next!=null&&fast.next.next!=null){fast=fast.next.next;slow=slow.next;}ListNode next=slow.next;if(next!=null&&next.next!=null){ListNode pre=next.next;while(pre!=null){/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
//保存下一节点
next.next=pre.next;
//pre节点插在slow节点之后,slow节点保持不动
pre.next=next;slow.next=pre;
//更新pre节点
pre=next.next;}merge(head,slow);}public void merge(ListNode head,ListNode slow){ListNode p=head;ListNode q=slow.next;while(q!=null&&p!=null){ //保存q的下一个节点
slow.next=q.next;
//将q插在p节点之后,尾插法
q.next=p.next;p.next=q;
//更新p、q节点
q=slow.next;p=p.next.next;}}}
第二种:
1.找到中间节点;
2.将后半部分节点入栈(出栈顺序与入栈顺序相反,所以一入一出就完成了链表后半部分的反转);
3.节点依次出栈,与入栈顺序相反,然后隔一个插入到前半部分中.
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ import java.util.Stack; public class Solution { public void reorderList(ListNode head) { if(head==null)return; ListNode fast=head,slow=head; while(fast.next!=null&&fast.next.next!=null){ fast=fast.next.next; slow=slow.next; } Stack<ListNode> stack=new Stack<ListNode>(); ListNode p=slow.next; while(p!=null){ stack.push(p); p=p.next; } slow.next=null; ListNode cur=head; while(cur!=null&&!stack.isEmpty()){ ListNode next=cur.next; cur.next=stack.pop(); cur.next.next=next; cur=next; } } }