We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// Create new list.
SinglyLinkedList list = new SinglyLinkedList();
// Merge sequence1 with list;
SinglyLinkedListNode head = head1;
while(head != null){
list.insertNode(head.data);
head = head.next;
}
// Merge sequence2 with list;
head = head2;
while(head != null){
list.insertNode(head.data);
head = head.next;
}
// First node.
SinglyLinkedListNode input = list.head;
// Anchor.
SinglyLinkedListNode sentinel = new SinglyLinkedListNode(0);
// Do while all items wont be added to sequence.
while(input != null){
// next to add.
SinglyLinkedListNode next = input;
// set new value to next iteration.
input = input.next;
SinglyLinkedListNode after = sentinel;
while(after.next != null && after.next.data < next.data){
after = after.next;
}
next.next = after.next;
after.next = next;
}
return sentinel.next;
}
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →
JAVA
Merge two sequence and sort it by "sorting by insert".
static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {