File tree 1 file changed +56
-0
lines changed
Pepcoding/Linked Lists/Add Last In Linked List
1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .io .*;
2
+ import java .util .*;
1
3
4
+ public class Main {
5
+ public static class Node {
6
+ int data ;
7
+ Node next ;
8
+ }
9
+
10
+ public static class LinkedList {
11
+ Node head ;
12
+ Node tail ;
13
+ int size ;
14
+
15
+ void addLast (int val ) {
16
+ // Write your code here
17
+ Node temp = new node ();
18
+ temp .data = val ;
19
+ temp .next = null ;
20
+
21
+ if (size == 0 ){
22
+ head = tail = temp ;
23
+ }else {
24
+ tail .next = temp ;
25
+ tail = temp ;
26
+ }
27
+ size ++;
28
+
29
+ }
30
+ }
31
+
32
+ public static void testList (LinkedList list ) {
33
+ for (Node temp = list .head ; temp != null ; temp = temp .next ) {
34
+ System .out .println (temp .data );
35
+ }
36
+ System .out .println (list .size );
37
+
38
+ if (list .size > 0 ) {
39
+ System .out .println (list .tail .data );
40
+ }
41
+ }
42
+ public static void main (String [] args ) throws Exception {
43
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
44
+ LinkedList list = new LinkedList ();
45
+
46
+ String str = br .readLine ();
47
+ while (str .equals ("quit" ) == false ){
48
+ if (str .startsWith ("addLast" )){
49
+ int val = Integer .parseInt (str .split (" " )[1 ]);
50
+ list .addLast (val );
51
+ }
52
+ str = br .readLine ();
53
+ }
54
+
55
+ testList (list );
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments