zoukankan      html  css  js  c++  java
  • leetcode之Reorder List

    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}.

    这道题分三步:

    1:首先将原来的链表拆分成两部分,用next和next.next分

    2:将第二部分链表反转

    3:将第一部分链表和第二部分反转了的链表merge

    Takeaway Messages from This Problem

    The three steps can be used to solve other problems of linked list. A little diagram may help better understand them.

    Reverse List:

    reverse-list

    Merge List:

    merge-list-in-place

    下面附上程序源码:

    public void reorderList(ListNode head) {
            if(head == null || head.next==null)  
    	    {  
    	        return;  
    	    }  
    	    ListNode walker = head;  
    	    ListNode runner = head;  
    	    while(runner.next!=null && runner.next.next!=null)  
    	    {  
    	        walker = walker.next;  
    	        runner = runner.next.next;  
    	    }  
    	    ListNode head1 = head;  
    	    ListNode head2 = walker.next;  
    	    walker.next = null;  
    	    head2 = reverse(head2);  
    	    while(head1!=null && head2!=null)  
    	    {  
    	        ListNode next = head2.next;  
    	        head2.next = head1.next;  
    	        head1.next = head2;  
    	        head1 = head2.next;  
    	        head2 = next;  
    	    }  
        }
        private ListNode reverse(ListNode head)  
    	{  
    	    ListNode pre = null;  
    	    ListNode cur = head;  
    	    while(cur!=null)  
    	    {  
    	        ListNode next = cur.next;  
    	        cur.next = pre;  
    	        pre = cur;  
    	        cur = next;  
    	    }  
    	    return pre;  
        }
    

      

  • 相关阅读:
    rs
    stm32f767 usoc3
    stm32f767 RTT 日志
    stm32f767 标准库 工程模板
    stm32f767 HAL 工程模板
    docker tab 补全 linux tab 补全
    docker anconda 依赖 下载 不了
    docker run 常用 指令
    linux scp 命令
    Dockerfile 常用参数说明
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4432402.html
Copyright © 2011-2022 走看看