每日AC--leetcode--recordList

来源:互联网 发布:西北师范知行教务管理 编辑:程序博客网 时间:2024/05/29 17:10




由于最近大脑短路的十分厉害, 表示很无奈

题目描述


Given a singly linked list LL 0L 1→…→L n-1L n,
reorder it to: L 0L n L 1L n-1L 2L n-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}.



AC代码:


public class ListNode {    public int val;    public ListNode next = null;    ListNode(int val) {        this.val = val;    }}


/** * 类说明 *  * <pre> * Modify Information: * Author        Date          Description * ============ =========== ============================ * DELL          2017年7月25日    Create this file * </pre> *  */public class LeetCodeRecordList {    /**     *         Given a singly linked list L: L 0→L 1→…→L n-1→L n,        reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.                  题目的意思和明显 0 1  2  3                    n n-1 n-2     * @param head     */    public void reorderList(ListNode head) {        // 链表的结构        // node1->node2->node3->null        ListNode rear = head;        ListNode tmp ; //构建新的链表 尾插法建立链表        while(head != null && head.next != null){            // 先定位到尾节点 前一个  例如这里算 node2            while(rear.next.next!= null){                rear = rear.next;            }                        tmp =  rear.next ; //取出尾节点后一个 比如  node3            rear.next = null; // 原队列node2的后一个置为null            tmp.next = head.next;             head.next = tmp;                         head = tmp.next; // 下一次循环从 node1 开始            rear = tmp.next;        }            }    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        ListNode node1 = new ListNode(1);        ListNode node2 = new ListNode(2);        ListNode node3 = new ListNode(3);        ListNode node4 = new ListNode(4);        node1.next = node2;        node2.next = node3;        node3.next = node4;        node4.next = null;        new LeetCodeRecordList().reorderList(node1);                while(node1 !=null){            System.out.println(node1.val);            node1 = node1.next;        }    }}


原创粉丝点击