频道栏目
首页 > 资讯 > 其他 > 正文

编程开发Reorder List求解

18-01-26        来源:[db:作者]  
收藏   我要投稿

编程开发Reorder List求解

Given a singly linked listL:L0→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.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if (head == null){
            return;
        }
        head = reverLastHalfNodes(head);
        ListNode fast = head, slow = head, first = head;
        while (fast != null&&fast.next != null&&fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode tmp = slow.next;
        slow.next = null;
        while (first != null){
            ListNode n0 = first.next;
            ListNode n1 = null;
            if (tmp != null){
                n1 = tmp.next;
                first.next = tmp;
                tmp.next = n0; 
            }
            tmp = n1;    
            first = n0;
        }
    }
    
    public ListNode reverLastHalfNodes(ListNode head){
        ListNode fast = head, slow = head;
        while (fast != null&&fast.next != null&&fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode tmp = slow;
        ListNode t = null;
        slow = slow.next;
        while (slow != null){
            ListNode n = slow.next;
            slow.next = t;
            t = slow;
            slow = n;
        }
        tmp.next = t;
        return head;
    }
}
相关TAG标签
上一篇:汇编语言:编写code段中代码,将a段和b段中的数据依次相加,将结果放到c段
下一篇:编程开发静态方法-static变量、static方法
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站