博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode--Reorder List
阅读量:4639 次
发布时间:2019-06-09

本文共 1782 字,大约阅读时间需要 5 分钟。

Given a singly linked list LL0→L1→…→Ln-1→Ln,

reorder it to: L0→LnL1→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}.

 

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public void reorderList(ListNode head) {        if(head != null){            ListNode stepOne = head, stepTwo = head;            while(stepTwo.next != null){                if(stepTwo.next != null)                    stepTwo = stepTwo.next;                if(stepTwo.next != null){                    stepTwo = stepTwo.next;                    stepOne = stepOne.next;                }            }            if(stepOne.next != null){                stepTwo = stepOne.next;                stepOne.next = null;                ListNode tailOfSecond = stepTwo;                stepOne = stepTwo;                if(stepTwo.next != null)                    stepTwo = stepTwo.next;                while(stepTwo.next != null){                    ListNode temp = stepTwo.next;                    stepTwo.next = stepOne;                    stepOne = stepTwo;                    stepTwo = temp;                }                stepTwo.next = stepOne;                tailOfSecond.next = null;            }            stepOne = head;            if(stepTwo != stepOne){                while(stepTwo != null){                    ListNode temp = stepOne.next;                    stepOne.next = stepTwo;                    stepOne = stepOne.next;                    stepTwo = temp;                }            }        }            }}

  

转载于:https://www.cnblogs.com/averillzheng/p/3552936.html

你可能感兴趣的文章
AVL树、splay树(伸展树)和红黑树比较
查看>>
多媒体音量条显示异常跳动
查看>>
运算符及题目(2017.1.8)
查看>>
React接入Sentry.js
查看>>
ssh自动分发密匙脚本样板
查看>>
转 小辉_Ray CORS(跨域资源共享)
查看>>
Linux安装postgresql
查看>>
MyBatis启动:MapperStatement创建
查看>>
【 全干货 】5 分钟带你看懂 Docker !
查看>>
[转]优化Flash性能
查看>>
popStar手机游戏机机对战程序
查看>>
Java Web项目结构
查看>>
lambda表达式树
查看>>
OpenCV YUV 与 RGB的互转(草稿)
查看>>
二次注入原理及防御
查看>>
会话记住已登录功能
查看>>
Linux内核分析——可执行程序的装载
查看>>
儿子和女儿——解释器和编译器的区别与联系
查看>>
第一阶段冲刺3
查看>>
父类引用指向子类对象
查看>>