重排链表
来源:互联网 发布:欧美电影推荐知乎 编辑:程序博客网 时间:2024/06/07 06:27
给定一个单链表L: L0→L1→…→Ln-1→Ln,
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。
样例
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。
样例
给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null。
import java.util.Scanner;import java.util.Stack;/** * 给定一个单链表L: L0→L1→…→Ln-1→Ln,重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…必须在不改变节点值的情况下进行原地操作。样例给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null。 * * @author Dell * */public class Test99 { public static void reorderList(ListNode head) { if(head==null||head.next==null) return; ListNode temp=new ListNode(-1); temp.next=head; ListNode mid=find(temp); ListNode later=mid.next; mid.next=null; Stack<ListNode> s=new Stack<>(); while(later!=null) { ListNode t=later; later=later.next; s.push(t); } ListNode p=temp.next; ListNode q=null; while(s.isEmpty()!=true&&p!=null) { q=p; p=p.next; ListNode zz=s.pop(); q.next=zz; zz.next=p; } } public static ListNode find(ListNode head) { ListNode slow=head.next; ListNode fast=head.next; while(fast.next!=null&&fast.next.next!=null) { slow=slow.next; fast=fast.next.next; } return slow; }public static void main(String[] args) {Scanner sc=new Scanner(System.in);int n=sc.nextInt();ListNode head=new ListNode(-1);ListNode p=head; for(int i=0;i<n;i++) { ListNode temp=new ListNode(sc.nextInt()); p.next=temp; p=p.next; } reorderList(head.next); ListNode q=head.next; while(q!=null) { System.out.print(q.val+" "); q=q.next; }}}
阅读全文
0 0
- 重排链表
- 重排链表
- 重排链表
- 重排链表
- LintCode:重排链表
- LintCode : 重排链表
- 重排链表
- 重排链表
- 重排链表-LintCode
- Reorder List 重排链表
- 算法:链表的重排
- Reorder List 链表重排
- L2-022. 重排链表
- lintcode(99)重排链表
- L2-022. 重排链表
- L2-022. 重排链表
- Java实现-重排链表
- L2-022. 重排链表
- RxJS异步通信之Subject和BehaviorSubject
- Android自定View-最简单的可拖拽式层叠卡片
- 模拟百度搜索框提示功能实例
- DrawerLayout 高仿QQ5.2双向侧滑菜单
- php利用堆栈 实现高级计算器
- 重排链表
- Java基础教程14-数组
- RLE行程长度压缩算法
- 马氏距离通俗理解
- 明天2辩。最差的进大组。我也很无奈。
- Sql Lite
- iOS 开发常用的框架
- Invalid bound statement (not found): com.shizongger.chapter2.mapper.UserMapper.insertUser
- urlib在python3的使用