Linked List

Linked List

Linked List

  • In a linked list, each data item is embedded in a link. A link is an object of a class called something like Link.
  • Each Link object contains a reference (usually called next) to the next link in the list.

What is references type ?

  • In Java a Link object doesn’t really contain another Link object.

  • The next field of type Link is only a reference to another link, not an object.

  • A reference is a number that refers to an object. (It’s the object’s address in the computer’s memory.)

    1. class Link {
    2. public int iData; // data item (key)
    3. public double dData; // data item
    4. public Link next; // next link in list
    5. // constructor
    6. public Link(int id, double dd) {
    7. iData = id; // initialize data
    8. dData = dd; // (‘next’ is automatically set to null)
    9. }
    10. // display ourself
    11. public void displayLink() {
    12. System.out.print(“{“ + iData + “, + dData + “} “);
    13. }
    14. }
    1. class LinkList {
    2. private Link first; // ref to first link on list
    3. // constructor
    4. public LinkList() {
    5. first = null; // no items on list yet
    6. }
    7. // true if list is empty
    8. public boolean isEmpty() {
    9. return (first==null);
    10. }
    11. // insert at start of list
    12. public void insertFirst(int id, double dd) {
    13. Link newLink = new Link(id, dd); // make new link
    14. newLink.next = first; // newLink --> old first
    15. first = newLink; // first --> newLink
    16. }
    17. // delete first item
    18. public Link deleteFirst() {
    19. Link temp = first; // save reference to link
    20. first = first.next; // delete it: first-->old next
    21. return temp; // return deleted link
    22. }
    23. public void displayList() {
    24. System.out.print(“List (first-->last): “);
    25. Link current = first; // start at beginning of list
    26. while(current != null) // until end of list,
    27. {
    28. current.displayLink(); // print data
    29. current = current.next; // move to next link
    30. }
    31. System.out.println(“”);
    32. }
    33. }

    Linked-List Efficiency

    • Insertion and deletion at the beginning of a linked list are very fast. (O(1))
    • Finding, deleting, or inserting next to a specific item requires searching. (O(N))
    • The linked list is nevertheless faster than array because nothing needs to be moved when an item is inserted or deleted.
    • A linked list uses exactly as much memory as it needs and can expand to fill all of available memory. (The size of an array is fixed when it’s created)

留言