-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_LinkedListImplementation.java
More file actions
64 lines (52 loc) · 1.37 KB
/
01_LinkedListImplementation.java
File metadata and controls
64 lines (52 loc) · 1.37 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
import java.util.*;
class ListNode {
int val;
ListNode next;
// Initialiser Block
{
val = 0;
next = null;
}
ListNode(){}
ListNode(int val){this.val = val;}
ListNode(int val, ListNode next){this.val = val; this.next = next;}
}
class Solution {
static ListNode createLinkedList(){
ListNode head = null, tail = null;
int n;
System.out.print("Enter the size of list: ");
// How to avoid this object.
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
while(n != 0){
int x;
System.out.print("Val: ");
x = sc.nextInt();
ListNode temp = new ListNode(x);
if (head != null) {
tail.next = temp;
tail = temp;
}
else {head = tail = temp;}
--n;
}
sc.close();
return head;
}
static void traverse(ListNode head){
System.out.println("\nTraversal: " + head);
ListNode p = head;
while(p != null){
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
ListNode head = createLinkedList();
traverse(head);
sc.close();
}
}