Example Linked List
From Java Example Source Code
Contents |
[edit] Overview - Example Linked List
This Java example program shows how to create and manipulate a linked list.
[edit] Java Source Code
- Package: example.linklist
- File: AnotherLinkList.java
package example.linklist; class Link { public int key; public double data; public Link next; public Link(int id, double dd) { key = id; data = dd; } public void displayLink() { System.out.print("{" + key + ", " + data + "} "); } } public class AnotherLinkList { private Link first; public AnotherLinkList() { first = null; } public void insertFirst(int id, double dd) { Link newLink = new Link(id, dd); newLink.next = first; first = newLink; } public Link find(int key) { Link current = first; while (current.key != key) { if (current.next == null) return null; // didn't find it else // not end of list, current = current.next; // go to next link } return current; // found it } // delete link with given key public Link delete(int key) { Link current = first; Link previous = first; while (current.key != key) { if (current.next == null) return null; // didn't find it else { previous = current; // go to next link current = current.next; } } // found it if (current == first) // if first link, first = first.next; // change first else // otherwise, previous.next = current.next; // bypass it return current; } public void displayList() { System.out.print("List (first to last): "); Link current = first; while (current != null) { current.displayLink(); current = current.next; } System.out.println(""); } public static void main(String[] args) { AnotherLinkList theList = new AnotherLinkList(); theList.insertFirst(12, 2.59); theList.insertFirst(24, 4.69); theList.insertFirst(36, 6.79); theList.insertFirst(48, 8.89); theList.displayList(); Link f = theList.find(44); if (f != null) System.out.println("Found link with key " + f.key); else System.out.println("Can't find link"); Link d = theList.delete(66); if (d != null) System.out.println("Deleted link with key " + d.key); else System.out.println("Can't delete link"); theList.displayList(); } }
[edit] What Result You Can Get
Coming soon...
[edit] Required External Libraries and/or Files for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
[edit] Question & Answer
Any question?
Click edit and post your question or answer here.
