300 likes | 534 Views
Singly Linked Lists. - Ed. 2, 3: Chapter 4 - Ed. 4.: Chapter 3. tail. pointer to a next node. node. pointer to an element. Illustration of a linked list in memory:. pointer to a next node. node. pointer to an element. pointer to a next node. node. pointer to an element.
E N D
Singly Linked Lists - Ed. 2, 3: Chapter 4- Ed. 4.: Chapter 3
pointer to a next node node pointer to an element Illustration of a linked list in memory:
pointer to a next node node pointer to an element
pointer to a next node node pointer to an element
pointer to a next node node pointer to an element
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; } }
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;
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);} }
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?
… … 0 1 9 Data Structure Exercises 5.1 Write a Java program to create a linked list as shown below. head tail