头条面试算法题

链表奇数位升序,偶数位降序,如何改为有序链表

package bytedance.linkedlist;

/**
 * @author Galip
 * @version 1.0
 * @date 2020/2/6 11:40
 */
public class OddEvenLinkedList {
    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(4);
        head.next.next = new Node(3);
        head.next.next.next = new Node(2);
        head.next.next.next.next = new Node(5);

        printList(oddEvenLinkedList(head));
    }

    private static class Node {
        Node next;
        int val;

        public Node(int val) {
            this.val = val;
        }
    }

    private static void printList(Node head) {
        while (head != null) {
            System.out.print(head.val + "->");
            head = head.next;
        }
    }

    public static Node oddEvenLinkedList(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        //将偶数链表拆分出来
        Node evenHead = getEvenList(head);
        //逆序偶数链表
        Node reEvenHead = reverseList(evenHead);
        //归并奇偶链表
        Node mHead = mergeList(head, reEvenHead);
        return mHead;
    }

    private static Node getEvenList(Node head) {
        Node cur = head;
        Node next = null;
        Node evenHead = head.next;

        while (cur != null && cur.next != null) {
            next = cur.next;
            cur.next = next.next;
            cur = cur.next;

            next.next = cur.next;
            next = next.next;
        }
        return evenHead;
    }

    private static Node reverseList(Node head) {
        Node pre = null;
        Node cur = head;
        Node next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    private static Node mergeList(Node head1, Node head2) {
        Node vHead = new Node(-1);
        Node cur = vHead;
        while (head1 != null && head2 != null) {
            if (head1.val < head2.val) {
                cur.next = head1;
                head1 = head1.next;
                cur = cur.next;
            } else {
                cur.next = head2;
                head2 = head2.next;
                cur = cur.next;
            }
        }
        cur.next = head1 == null ? head2 : head1;
        return vHead.next;
    }


}
全部评论
链表偶数部分拆分出来的时候就可以通过“尾插法”实现反转吧?
点赞 回复 分享
发布于 2021-02-02 15:47

相关推荐

斑驳不同:还为啥暴躁 假的不骂你骂谁啊
点赞 评论 收藏
分享
10-30 10:16
南京大学 Java
龚至诚:给南大✌️跪了
点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务