class ListElement { ListElement next; // a pointer to the next element int data; // data }
class List { private ListElement head; // a pointer to the first element private ListElement tail;
void add(int data) { // adding to the end of the list ListElement a = new ListElement(); //create a new item a.data = data; if (tail == null) //If the list is empty { //that link points to start and end with a new element head = a; //i.e. list now consists of a single element tail = a; } else { tail.next = a; //otherwise the "old" last element now refers to the new tail = a; //and a pointer to the last element of the address of the new record } }
void printList() //print list { ListElement t = head; //to get a reference to the first element while (t != null) //there is an element { System.out.print(t.data + " "); //print its data t = t.next; //and switch to the next } } }
public class Main { public static void main(String[] args) { List list = new List(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5);
Comments
Leave a comment