Skip to content

Instantly share code, notes, and snippets.

@pedrofurtado
Created January 3, 2016 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrofurtado/e51e40aa248a3ea43b2b to your computer and use it in GitHub Desktop.
Save pedrofurtado/e51e40aa248a3ea43b2b to your computer and use it in GitHub Desktop.
Implementation of Singly Linked List in Java.
/**
* @file
* Singly linked list.
*/
public class SinglyLinkedList {
public int key;
public SinglyLinkedList next;
/**
*
*/
public SinglyLinkedList get_last(SinglyLinkedList begin) {
if (begin == null) return null;
SinglyLinkedList p = begin;
while(p.next != null) p = p.next;
return p;
}
public SinglyLinkedList get_by_key(SinglyLinkedList begin, int key) {
if (begin == null) return null;
SinglyLinkedList p = begin;
while(p != null) {
if (p.key == key) return p;
p = p.next;
}
return null;
}
// i vale de 1 até infinito.
public SinglyLinkedList get_nesim(SinglyLinkedList begin, int i) {
if (begin == null) return null;
SinglyLinkedList p = begin;
int n = 1;
while((p != null) && (n < i)) {
p = p.next;
n++;
}
if (n == i) return p;
return null;
}
public SinglyLinkedList get_previous(SinglyLinkedList begin, SinglyLinkedList node) {
if ((begin == null) || (node == null)) return null;
SinglyLinkedList p = begin;
while(p != null) {
if (p.next == node) return p;
p = p.next;
}
return null;
}
public boolean is_empty(SinglyLinkedList begin) {
return begin == null;
}
public void print_list(SinglyLinkedList begin) {
if (begin == null) {
System.out.println("Empty list.");
return;
}
System.out.println();
System.out.print("List: ");
SinglyLinkedList p = begin;
while(p != null) {
System.out.print(p.key + ", ");
p = p.next;
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment