Singly Linked Lists - Ed. 2, 3: Chapter 4 - Ed. 4.: Chapter 3
tail
pointer to a next node pointer to an element node Illustration of a linked list in memory:
pointer to a next node pointer to an element node
pointer to a next node pointer to an element node
pointer to a next node pointer to an element node
Singly Linked Lists and Arrays
Class Node Here is an implementation of nodes in Java: public class Node { private Object element; private Node next; public Node() { this( null, null ); } public Node( Object e, Node n ) { element = e; next = n; }
Object getElement() { return element } Node getNext() { return next; } void setElement( Object newElem ) { element = newElem; } void setNext( Node newNext ) { next = newNext; } }
Insertion of an Element at the Head
Node x = new Node(); x.setElement(new String(“Baltimore”)); The following statement is not correct: x.element = new String(“Baltimore”));
x.setNext(head); head = x;
Deleting an Element at the Head
head = head.getNext();
Insertion of an Element at the Tail
Node x = new Node( ); x.setElement(new String(“Baltimore”)); x.setNext(null); tail.setNext(x); tail = x;
How to keep “head” and “tail”? public class Head_and_Tail { Node head; Node tail; Head_and_Tail(Node x, Node y) { head = x; tail = y; }
How to keep “head” and “tail”? public class GeneratingList { Node head = null; Node tail = null; Public Head_and_Tail linked_list () { Node x = null; for (int i = 0; i < 10; i++) {x = new Node(); x.setElement(new Integer(i)); if (i == 0 ) {x.setNext(null); tail = x;} else x.setNext(head); head = x; } return new Head_and_Tail(head, tail);} }
Deleting an Element at the Tail
should be removed
How to insert a new node in the middle of a singly linked list? How to remove a node which in the middle of a singly linked list?
Data Structure Exercises 5.1 Write a Java program to create a linked list as shown below. 019 … headtail
public class ListStack implements Stack { private int size = 0; private Node head = null; public ListStack() {} public int size() { return size; } public boolean isEmpty() { return size == 0; } public void push( Object obj ){ Node x = new Node(); x.setElement(obj); x.setNet(head); head = x; size++; }
public object pop() throws StackEmptyException { if( isEmpty() ) throw new StackEmptyException( "Stack is Empty." ); Object elem = head; head = getNext(head); size--; return elem; } public object top() throws StackEmptyException { if( isEmpty() ) throw new StackEmptyException( "Stack is Empty." ); return head;; }