public class Node { private int data; private Node link; public Node() { data = 0; link = null; } public int getData() { return data; } public Node getLink() { return link; } public void setData(int d) { data = d; } public void setLink(Node l) { link = l; } }
public class List { private Node head; private int count; public List() { head = null; count = 0; } public boolean isEmpty() { return (count == 0); } public int getSize() { return count; } public int getElement(int index) { if(index < 0 || index > count) return -1; Node walker = head; for(int i = 0; i < index; i++) walker = walker.getLink(); return walker.getData(); } public String toString() { String str = "["; Node walker = head; while(walker != null) { str = str + " " + walker.getData(); walker = walker.getLink(); } return str+" ]"; } public boolean search(int element) { Node walker = head; while(walker != null && walker.getData() != element) walker = walker.getLink(); if(walker == null) return false; else return true; } public boolean insert(int element, int index) { if(index < 0 || index > count) return false; Node newNode = new Node(); newNode.setData(element); if(index == 0) { newNode.setLink(head); head = newNode; count++; return true; } Node walker = head; for(int i = 0; i < index-1; i++) walker = walker.getLink(); newNode.setLink(walker.getLink()); walker.setLink(newNode); count++; return true; } public boolean delete(int index) { if(index < 0 || index > count-1) return false; if(index == 0) { head = head.getLink(); count--; return true; } Node walker = head; for(int i = 0; i < index-1; i++) walker = walker.getLink(); walker.setLink(walker.getLink().getLink()); count--; return true; } }
import java.util.Random; public class ListTest { public static void main(String args[]) { Random r = new Random(); List l = new List(); for(int i = 0; i < 11; i++) l.insert(r.nextInt(100), i); System.out.println(l); //insert l.insert(100, 5); System.out.println(l); //delete l.delete(10); System.out.println(l); } }