package tugas;
/**
*
* @author Fadil
*/
public class SingleLinked {
protected Node head;
protected Node tail;
//if head is null, return true
public boolean isEmpty() {
if (this.head == null) {
return true;
} else {
return false;
}
}
//get first element
public String first(){
if(isEmpty() == true){
return null;
}else{
return head.getElement();
}
}
//get last element
public String last(){
if(this.tail == null){
return null;
}else{
return tail.getElement();
}
}
//this is for add from tail
public void append(String item){
Node tampung = new Node(item, null);
if(isEmpty()){
head = tampung;
}else{
tail.setNext(tampung);
}
tail = tampung;
}
//this is for add from head
public void prepend(String item){
Node tampung = new Node(item, null);
if(isEmpty()){
head = tampung;
}else{
tampung.setNext(head);
}
head = tampung;
}
//display all Node
public void Display(){
Node ptr;
ptr = head;
while(ptr != null){
System.out.println(ptr.getElement());
ptr = ptr.getNode();
}
}
//Search Node to Remove
public Node removeNode(String item){
Node ptr = head;
Node prevPtr = head;
while(ptr.getElement() != item){
if(ptr.isHasNext() == false){
return null;
}else{
prevPtr = ptr;
ptr = ptr.getNode();
}
}
if(ptr == prevPtr){
head = ptr.getNode();
}else{
prevPtr.setNext(ptr.getNode());
}
return ptr;
}
//Remove first Node(Head)
public String ExtractFirst(){
if(this.head == null){
return "Data masih kosong";
}
String forReturn = this.head.getElement();
this.head = head.getNode();
return forReturn;
}
public static void main(String[] args) {
SingleLinked myList = new SingleLinked(); //create a new empty linked list
myList.append("Amin");
myList.append("Budi");
myList.append("Citra");
myList.Display();
myList.removeNode("Citra");
System.out.println("");
myList.Display();
}
}
class Node {
private String element;
private Node next;
public Node(String element, Node next) {
this.element = element;
this.next = next;
}
public String getElement() {
return this.element;
}
public boolean isHasNext() {
if (next == null) {
return false;
} else {
return true;
}
}
public Node getNode() {
return next;
}
public void setElement(String newElement) {
element = newElement;
}
public void setNext(Node newNode) {
next = newNode;
}
}
Simple Single Linked List
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.