题解 | #重排链表#

重排链表

http://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if(head==null || head.next==null) return;
        List<ListNode> nodes = new ArrayList<>();
        ListNode cur = head;
        while(cur!=null){ // 将链表保存到list里
            nodes.add(cur);
            cur = cur.next;
        }
        cur = head;
        for (int i = 0; i < nodes.size()/2; i++) { // 组装
            ListNode right = nodes.get(nodes.size() - i - 1);
            right.next = cur.next;
            cur.next = right;
            cur = right.next;
        }
        cur.next = null;
    }
}
全部评论

相关推荐

深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务