-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMLinkedList.java
More file actions
117 lines (81 loc) · 2.33 KB
/
Copy pathMLinkedList.java
File metadata and controls
117 lines (81 loc) · 2.33 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
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
import java.util.*;
class Mlinkedlist {
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
Node head = null;
void CreateList() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of nodes: ");
int n = sc.nextInt();
Node temp = null;
for (int i = 1; i <= n; i++) {
System.out.println("Enter data: ");
int v = sc.nextInt();
Node newnode = new Node(v);
if (head == null) {
head = temp = newnode;
}
else {
temp.next = newnode;
temp = newnode;
}
}
}
// Display Linked List
void display() {
Node p = head;
if (p == null) {
System.out.println("Sorry, It is empty.");
return;
}
while (p != null) {
System.out.print(p.data + "--->");
p = p.next;
}
System.out.println("NULL");
}
// Merge two linked lists
void merge(Mlinkedlist list2) {
// If first list is empty
if (head == null) {
head = list2.head;
return;
}
// If second list is empty
if (list2.head == null) {
return;
}
Node temp = head;
// Go to the last node of first list
while (temp.next != null) {
temp = temp.next;
}
// Connect last node of first list
// to first node of second list
temp.next = list2.head;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Mlinkedlist list1 = new Mlinkedlist();
Mlinkedlist list2 = new Mlinkedlist();
System.out.println("Enter elements for First Linked List:");
list1.CreateList();
System.out.println("\nEnter elements for Second Linked List:");
list2.CreateList();
System.out.println("\nFirst Linked List:");
list1.display();
System.out.println("\nSecond Linked List:");
list2.display();
// Merge list2 into list1
list1.merge(list2);
System.out.println("\nAfter Merging:");
list1.display();
sc.close();
}
}