-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path(Linked List) Get Value in Linked List
134 lines (120 loc) · 2.94 KB
/
(Linked List) Get Value in Linked List
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import java.io.*;
import java.util.*;
public class Main {
public static class Node {
int data;
Node next;
}
public static class LinkedList {
Node head;
Node tail;
int size;
void addLast(int val) {
Node temp = new Node();
temp.data = val;
temp.next = null;
if (size == 0) {
head = tail = temp;
} else {
tail.next = temp;
tail = temp;
}
size++;
}
public int size(){
return size;
}
public void display(){
for(Node temp = head; temp != null; temp = temp.next){
System.out.print(temp.data + " ");
}
System.out.println();
}
public void removeFirst(){
if(size == 0){
System.out.println("List is empty");
} else if(size == 1){
head = tail = null;
size = 0;
} else {
head = head.next;
size--;
}
}
public int getFirst(){
// write your code here
if(size == 0){
System.out.println("List is empty");
return -1;
}
else
return head.data;
}
public int getLast(){
// write your code here
if(size == 0){
System.out.println("List is empty");
return -1;
}
else
return tail.data;
}
public Node getNnode(int pos){
Node temp = head;
while(pos>0){
temp = temp.next;
pos--;
}
return temp;
}
public int getAt(int idx){
// write your code here
if(size ==0){
System.out.println("List is empty");
return -1;
}
else if(idx>=size || idx<0){
System.out.println("Invalid arguments");
return -1;
}
else{
Node n = getNnode(idx);
return n.data;
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LinkedList list = new LinkedList();
String str = br.readLine();
while(str.equals("quit") == false){
if(str.startsWith("addLast")){
int val = Integer.parseInt(str.split(" ")[1]);
list.addLast(val);
} else if(str.startsWith("size")){
System.out.println(list.size());
} else if(str.startsWith("display")){
list.display();
} else if(str.startsWith("removeFirst")){
list.removeFirst();
} else if(str.startsWith("getFirst")){
int val = list.getFirst();
if(val != -1){
System.out.println(val);
}
} else if(str.startsWith("getLast")){
int val = list.getLast();
if(val != -1){
System.out.println(val);
}
} else if(str.startsWith("getAt")){
int idx = Integer.parseInt(str.split(" ")[1]);
int val = list.getAt(idx);
if(val != -1){
System.out.println(val);
}
}
str = br.readLine();
}
}
}