import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pHead1 ListNode类
     * @param pHead2 ListNode类
     * @return ListNode类
     */
    public ListNode Merge (ListNode pHead1, ListNode pHead2) {
        // write code here
        if (pHead1 == null) return pHead2;
        if (pHead2 == null) return pHead1;
        ListNode temp1 = pHead1;
        ListNode temp2 = pHead2;
        List<Integer> intList = new ArrayList<>();
        List<ListNode> nodeList = new ArrayList<>();
        intList.add(temp1.val);
        nodeList.add(temp1);
        intList.add(temp2.val);
        nodeList.add(temp2);
        while (true) {
            if (temp1 != null) {
                ListNode next1 = temp1.next;
                if (next1 != null) {
                    intList.add(next1.val);
                    nodeList.add(next1);
                    temp1 = next1;
                } else {
                    temp1 = null;
                }
            }

            if (temp2 != null) {
                ListNode next2 = temp2.next;
                if (next2 != null) {
                    intList.add(next2.val);
                    nodeList.add(next2);
                    temp2 = next2;
                } else {
                    temp2 = null;
                }
            }
            if(temp1 == null && temp2 == null) break;
        }

        intList.sort(Integer::compareTo);
        ListNode startNode = null;
        ListNode loopNode = null;
        for (int i = 0; i < intList.size(); i++) {
            int val = intList.get(i);
            if (i == 0) {
                for (int j = 0; j < nodeList.size(); j++) {
                    ListNode tempNode = nodeList.get(j);
                    if (val == tempNode.val) {
                        loopNode = tempNode;
                        startNode = loopNode;
                        tempNode.next = null;
                        break;
                    }
                }
                continue;
            }
            for (int j = 0; j < nodeList.size(); j++) {
                ListNode tempNode = nodeList.get(j);
                if (val == tempNode.val) {
                    if (loopNode == tempNode) continue;
                    loopNode.next = tempNode;
                    tempNode.next = null;
                    loopNode = tempNode;
                }
            }
        }

        return startNode;
    }
}