Repository navigation
Expand file tree
/
Copy pathMyLinkedList.java
More file actions
90 lines (69 loc) · 2 KB
/
Copy pathMyLinkedList.java
File metadata and controls
90 lines (69 loc) · 2 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
80
81
82
83
84
85
86
87
88
89
90
package com.hellokoding.datastructure;
public class MyLinkedList {
Node head;
public void addFirst(int data) {
if (head == null) {
head = new Node(data);
return;
}
Node newNode = new Node(data);
newNode.next = this.head;
this.head = newNode;
}
public void addLast(int data) {
if (head == null) {
head = new Node(data);
return;
}
Node currentNode = this.head;
while (currentNode.next != null) {
currentNode = currentNode.next;
}
currentNode.next = new Node(data);
}
public void removeFirst() {
if (this.head == null) return;
this.head = this.head.next;
}
public void removeLast() {
if (this.head == null) return;
if (this.head.next == null) {
this.head = null;
return;
}
Node currentNode = this.head;
while (currentNode.next.next != null) {
currentNode = currentNode.next;
}
currentNode.next = null;
}
public void traversal() {
Node currentNode = this.head;
while (currentNode != null) {
System.out.printf("%d ", currentNode.data);
currentNode = currentNode.next;
}
System.out.println();
}
public static void main(String[] args) {
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addLast(2);
myLinkedList.addLast(6);
myLinkedList.addFirst(9);
System.out.println("Traverse all elements");
myLinkedList.traversal();
System.out.println("Remove first node");
myLinkedList.removeFirst();
myLinkedList.traversal();
System.out.println("Remove last node");
myLinkedList.removeLast();
myLinkedList.traversal();
}
static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
}