• 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;  
        }
    

      

  • 相关阅读:
    hdu 3832 Earth Hour
    hdu 2112 HDU Today
    hdu 2473 Junk-Mail Filter
    hdu 1558 Segment set
    5-2学习记录|5-3日
    看面经
    2020-5-1学习记录
    2020-4-30学习记录
    2020-4-27学习记录
    4.19日学习笔记
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4432402.html
Copyright © 2020-2023  润新知