|
| 1 | +package me.ramswaroop.linkedlists; |
| 2 | + |
| 3 | +import me.ramswaroop.common.SingleLinkedList; |
| 4 | +import me.ramswaroop.common.SingleLinkedNode; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by IntelliJ IDEA. |
| 8 | + * |
| 9 | + * @author: ramswaroop |
| 10 | + * @date: 7/13/15 |
| 11 | + * @time: 12:54 PM |
| 12 | + */ |
| 13 | +public class MergeTwoLinkedListAlternatively { |
| 14 | + |
| 15 | + /** |
| 16 | + * Given two linked lists, insert nodes of second list into first list at |
| 17 | + * alternate positions of first list till there are no more positions to |
| 18 | + * insert in first list. |
| 19 | + * <p/> |
| 20 | + * Example, |
| 21 | + * Input: L1: 5->7->17->13->11 and L2: 12->10->2->4->6 |
| 22 | + * Output: L1: 5->12->7->10->17->2->13->4->11->6 and L2: empty |
| 23 | + * <p/> |
| 24 | + * Input: L1: 1->2->3 and L2: 4->5->6->7->8 |
| 25 | + * Output: L1: 1->4->2->5->3->6 and L2: 7->8 |
| 26 | + * |
| 27 | + * @param node1 |
| 28 | + * @param node2 |
| 29 | + * @param <E> |
| 30 | + * @return |
| 31 | + */ |
| 32 | + public static <E extends Comparable<E>> SingleLinkedNode<E> mergeTwoLinkedListAlternatively(SingleLinkedNode<E> node1, |
| 33 | + SingleLinkedNode<E> node2) { |
| 34 | + |
| 35 | + SingleLinkedNode<E> curr1 = node1, curr2 = node2, temp1, temp2; |
| 36 | + |
| 37 | + while (curr1 != null && curr2 != null) { |
| 38 | + temp1 = curr1.next; |
| 39 | + temp2 = curr2.next; |
| 40 | + |
| 41 | + curr1.next = curr2; |
| 42 | + curr2.next = temp1; |
| 43 | + |
| 44 | + curr1 = temp1; |
| 45 | + curr2 = temp2; |
| 46 | + } |
| 47 | + |
| 48 | + return curr2; |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + public static void main(String a[]) { |
| 53 | + SingleLinkedList<Integer> linkedList1 = new SingleLinkedList<>(); |
| 54 | + linkedList1.add(00); |
| 55 | + linkedList1.add(11); |
| 56 | + linkedList1.add(22); |
| 57 | + linkedList1.add(33); |
| 58 | + linkedList1.add(44); |
| 59 | + linkedList1.add(55); |
| 60 | + linkedList1.printList(); |
| 61 | + SingleLinkedList<Integer> linkedList2 = new SingleLinkedList<>(); |
| 62 | + linkedList2.add(21); |
| 63 | + linkedList2.add(33); |
| 64 | + linkedList2.add(44); |
| 65 | + linkedList2.add(55); |
| 66 | + linkedList2.add(67); |
| 67 | + linkedList2.add(89); |
| 68 | + linkedList2.add(99); |
| 69 | + linkedList2.printList(); |
| 70 | + SingleLinkedNode<Integer> list2 = mergeTwoLinkedListAlternatively(linkedList1.head, linkedList2.head); |
| 71 | + linkedList1.printList(); |
| 72 | + SingleLinkedList.printList(list2); |
| 73 | + } |
| 74 | +} |
0 commit comments