Linear Data Structures_ Linked Lists Cheatsheet _ Codecademy
Linear Data Structures_ Linked Lists Cheatsheet _ Codecademy
Linked Lists
Linked List Overview
A Java LinkedList class can implement a public public void addToHead(String data) {
void .addToHead() instance method for adding
Node newHead = new Node(data);
new data to the head of the list. .addToHead()
takes a single String data argument. It uses Node currentHead = this.head;
data to create a new Node which it adds to the this.head = newHead;
head of the list. if (currentHead != null) {
this.head.setNextNode(currentHead);
}
}
Adding to the Tail
A Java LinkedList class can implement a public public void addToTail(String data) {
void .addToTail() instance method for adding
Node tail = this.head;
new data to the tail of the list. .addToTail()
takes a single String data argument. It uses if (tail == null) {
data to create a new Node which it adds to the this.head = new Node(data);
tail of the list. } else {
while (tail.getNextNode() != null) {
tail = tail.getNextNode();
}
tail.setNextNode(new Node(data));
}
}
Print Share