forked from vishnu2k60/HacktoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinkedIntList.java
85 lines (76 loc) · 2.42 KB
/
LinkedIntList.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
// Int Node
class ListNode {
int value;
ListNode next;
}
// A LinkedIntList stores a list of integers
public class LinkedIntList {
private ListNode front; // The front node of the linked list
public LinkedIntList(int ...a) {
// Constructor of LinkedIntList class with avriable number of integer arguements
front = null;
for (int i:a) {
// Inserting int arguments in the linked list one by one
ListNode newnode = new ListNode(); // Creating new list node
newnode.value = i;
newnode.next = null;
if(front == null) {
// if list contains no node
front = newnode;
}
else {
ListNode cur = front;
while(cur.next != null) {
// finding the position for the insertion of the new node
cur = cur.next;
}
cur.next = newnode;
}
}
}
@Override
public String toString() {
// Overrides toString method for LinkedIntList object
String output = "";
ListNode cur = front;
while (cur != null) {
output = output.concat(" " + String.valueOf(cur.value));
cur = cur.next;
}
return output;
}
public void doubleUp() {
// This function doubles up the size of the linked list by inserting a copy of each node
if(front == null) {
// if list is empty
System.out.println("The list is empty!");
return;
}
ListNode cur = front;
while(cur != null) {
// Creating a duplicate node
ListNode newnode = new ListNode();
newnode.value = cur.value;
newnode.next = cur.next;
// inserting node after current node
cur.next = newnode;
cur = newnode.next;
}
}
public void MyFun() {
ListNode h = front;
while(h != null) {
System.out.print(h.value + "->");
h = h.next.next;
}
}
public static void main(String[] args) {
LinkedIntList list = new LinkedIntList(2, 1, 3, 9, 5, 3, 7, 4);
//list.doubleUp();
System.out.println();
list.MyFun();
LinkedIntList list2 = new LinkedIntList(1, 2, 3, 4, 5, 6, 7);
System.out.println();
list2.MyFun();
}
}