-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnion_in_ll.java
More file actions
79 lines (56 loc) · 1.58 KB
/
Union_in_ll.java
File metadata and controls
79 lines (56 loc) · 1.58 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
/*******
* Following is the LinkedListNode structure
class ListNode<T> {
T data;
ListNode<T> next;
ListNode(T data)
{
this.data=data;
next = null;
}
}
*********/
public class solution {
public static boolean isPresent(ListNode<Integer> head, int data){
while(head != null){
if (head.data == data){
return true;
}
head = head.next;
}
return false;
}
public static ListNode<Integer> Union(ListNode<Integer> head1, ListNode<Integer> head2) {
ListNode<Integer> temp = null;
while(head1 != null){
ListNode<Integer> new_node = new ListNode<Integer>(head1.data);
new_node.next = temp;
temp = new_node;
// print(temp);
head1 = head1.next;
}
while(head2 != null){
// System.out.println(head2.data);
if(!isPresent(temp,head2.data)){
ListNode<Integer> new_node = new ListNode<Integer>(head2.data);
new_node.next = temp;
temp = new_node;
}
head2 = head2.next;
}
return reverse(temp);
}
private static ListNode reverse(ListNode<Integer> head){
ListNode current = head;
ListNode next = null;
ListNode prev = null;
while ( current != null)
{
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}