码迷,mamicode.com
首页 > 其他好文 > 详细

reorder-list

时间:2017-05-24 00:43:11      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:list   不同   ret   link   last   bsp   int   containe   val   

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
//思路:通过不同的首结点获取到不同的尾结点,然后拼接
public class Solution {
   public ListNode getLastNode(ListNode head)
    {
        ListNode first = head;
        ListNode fakeLast = head;
        if (head.next == null)
        {
            return head;
        }
        while (first.next != null)
        {
            fakeLast = first;
            first = first.next;
        }
        ListNode last = fakeLast.next;
        fakeLast.next = null;
        return last;
    }
 
    public void reorderList(ListNode head)
    {
       if(head==null){
            return;
        }
        // 真的首结点
        ListNode first = head;
        // 假的首结点
        ListNode fakeFirst = head;
        while (first.next != null)
        {
            ListNode last = getLastNode(first);
            fakeFirst = first.next;
            if (fakeFirst == null)
            {
                first.next = last;
                break;
            }
            else
            {
                first.next = last;
                last.next = fakeFirst;
                first = fakeFirst;
            }
 
        }
    }
}

 

reorder-list

标签:list   不同   ret   link   last   bsp   int   containe   val   

原文地址:http://www.cnblogs.com/qingtianBKY/p/6896754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!