This repository was archived by the owner on Apr 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathMergeTwoSortedLists.java
More file actions
76 lines (46 loc) · 1.4 KB
/
MergeTwoSortedLists.java
File metadata and controls
76 lines (46 loc) · 1.4 KB
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
/*-- Merging two sorted Linked Lists --*/
import java.util.*;
public class MergeTwoSortedLists {
/*-- Merging two sorted Lists method --*/
public static Node mergeTwoSortedLists(Node A, Node B) {
LinkedList<Integer> list = new LinkedList<>();
while(A!=null){
list.add(A.data);
A = A.next;
}
while(B!=null){
list.add(B.data);
B = B.next;
}
Collections.sort(list);
Node llist = new Node(list.get(0));
Node n = llist;
for(int i=1; i<list.size(); i++){
n.next = new Node(list.get(i));
n = n.next;
}
return llist;
}
/*-- Inputs from the main method --*/
public static void main(String[] args){
Node A = new Node(10);
A.next = new Node(20);
A.next.next = new Node(30);
Node B = new Node(40);
B.next = new Node(50);
B.next.next = new Node(60);
Node C = mergeTwoSortedLists(A,B);
while(C!=null){
System.out.println(C.data);
C = C.next;
}
}
}
/*-- Node class Implementation --*/
class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
}