题解 | #重排链表#

重排链表

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

import java.util.*;
/**
 * 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) {
            return;
        }
        ListNode pNode = new ListNode(0);
        pNode.next = head;

        List<ListNode> list = new ArrayList<>();
        while (pNode.next != null) {
            pNode = pNode.next;
            list.add(pNode);
        }

        List<ListNode> list1 = new ArrayList<>(list.size());
        for (int i = 0; i < list.size(); i ++) {
            if (i == 0) {
                list1.add(list.get(i));
                continue;
            }
            if (i % 2 == 0) {
                list1.add(list.get(i / 2));
            } else {
                list1.add(list.get(list.size() - 1 - i / 2));
            }
        }

        for (int i = 0; i < list1.size() - 1; i ++) {
            list1.get(i).next = list1.get(i + 1);
        }
        list1.get(list.size() - 1).next = null;
    }
}

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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