data-structures/java/SList/Link.java

39 lines
1.1 KiB
Java
Raw Permalink Normal View History

2022-09-12 13:17:38 +00:00
/** Singly linked list node */
class Link<T> {
private T element; // Value for this node
private Link<T> next; // Pointer to next node in list
// Constructors
Link(T it, Link<T> nextVal)
{ element = it; next = nextVal; }
Link(Link<T> nextVal) { next = nextVal; }
Link<T> next() {return next; } // Return nrxt field
Link<T> setNext(Link<T> nextVal) // Set next field
{ return next = nextVal; } // Return element field
T element() { return element; } // Set element field
T setElement(T it) { return element = it; }
/** Extensions to support freelists */
static Link freelist = null; // Freelist for the class
/** @return A new link */
static <T> Link<T> get(Tit, Link<T> nextVal) {
if (freelist == null)
return new Link<T>(it, nextVal); // Get from "new"
Link<T> temp = freelist; // Get from freelist
freelist = freelist.next();
temp.setElement(it);
temp.setNext(nextVal);
return temp;
}
/** Return a link to the freelist */
void release() {
element = null; // Drop reference to the element
next = freelist;
freelist = this;
}
}