-
Notifications
You must be signed in to change notification settings - Fork 29
/
merge_two_sorted_linkedlist.java
121 lines (94 loc) · 2.96 KB
/
merge_two_sorted_linkedlist.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.io.*;
import java.util.*;
public class Main {
public static class Node {
int data;
Node next;
}
public static class LinkedList {
Node head;
Node tail;
int size;
void addLast(int val) {
Node temp = new Node();
temp.data = val;
temp.next = null;
if (size == 0) {
head = tail = temp;
} else {
tail.next = temp;
tail = temp;
}
size++;
}
public int size() {
return size;
}
public void display() {
for (Node temp = head; temp != null; temp = temp.next) {
System.out.print(temp.data + " ");
}
System.out.println();
}
public void addFirst(int val) {
Node temp = new Node();
temp.data = val;
temp.next = head;
head = temp;
if (size == 0) {
tail = temp;
}
size++;
}
public static LinkedList mergeTwoSortedLists(LinkedList l1, LinkedList l2) {
LinkedList res = new LinkedList();
Node o=l1.head;
Node t=l2.head;
while(o!=null && t!=null)
{
if(o.data<t.data)
{
res.addLast(o.data);
o=o.next;
}
else
{
res.addLast(t.data);
t=t.next;
}
}
while(o!=null)
{
res.addLast(o.data);
o=o.next;
}
while(t!=null)
{
res.addLast(t.data);
t=t.next;
}
return res;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n1 = Integer.parseInt(br.readLine());
LinkedList l1 = new LinkedList();
String[] values1 = br.readLine().split(" ");
for (int i = 0; i < n1; i++) {
int d = Integer.parseInt(values1[i]);
l1.addLast(d);
}
int n2 = Integer.parseInt(br.readLine());
LinkedList l2 = new LinkedList();
String[] values2 = br.readLine().split(" ");
for (int i = 0; i < n2; i++) {
int d = Integer.parseInt(values2[i]);
l2.addLast(d);
}
LinkedList merged = LinkedList.mergeTwoSortedLists(l1, l2);
merged.display();
// example inputs are l1: 10 20 30 40 50
// l2: 7 9 12 15 37 43 44 48 52 56
}
}