Merge two sorted linked lists

  • + 0 comments

    Java with some sorting

    List<SinglyLinkedListNode> l = new ArrayList<>();
    while (head1 != null || head2 != null) {
    	if (head1 != null) {
    		l.add(head1);
    	}
    	if (head2 != null) {
    		l.add(head2);
    	}
    	head1 = head1 != null ? head1.next : null;
    	head2 = head2 != null ? head2.next : null;
    }
    l = l.stream()
    	.sorted(Comparator.comparingInt(n -> n.data))
    	.collect(java.util.stream.Collectors.toList());
    for (int i = 0; i < l.size() - 1; i++) {
    	SinglyLinkedListNode c = l.get(i);
    	c.next = l.get(i+1);
    }
    return l.get(0);