Doubly link list question

I desparately need help with these topic. Currently, I am doing a project using doubly link list data structure and swing components. However, I just could not get the data items of the doubly link list to display on the JTextArea. Is this possible at all or does anybody out there know in anyway to solve this problem?

Thanks a lot for the timely reply amolk. Here is the sample code you request for:
//The following code is my Link class:
import java.io.Serializable;
public class Link implements Serializable
public String dTitle, dPublisher, dCategory, dUserlevel, dDescription, dISBN, dDay, dMonth, dYear;
public float dPrice;
public int dQuantity;
public Link next; // next link in list
public Link previous; // previous link in list
public Link(String tit, String pub, String cat, float price, int qty, String ISBN, String day, String month, String year, String level, String des) // constructor
dTitle = tit;
dPublisher = pub;
dCategory = cat;
dPrice = price;
dQuantity = qty;
dISBN = ISBN;
dDay = day;
dMonth = month;
dYear = year;
dUserlevel = level;
dDescription = des;
public void displayLink()
System.out.println(dTitle + "");
} // end class Link
//The following is the actual doubly link list code
import java.io.Serializable;
public class DoublyLinkedList implements Serializable
public String back;
public boolean notFound = false;
private Link first; // ref to first item
private Link last; // ref to last item
public DoublyLinkedList() // constructor
first = null; // no items on list yet
last = null;
public boolean isEmpty() // true if no links
return first==null;
public void insertFirst(String title, String publisher, String category, float price, int quantity, String ISBN, String day, String month, String year, String userlevel, String description) // insert at front of list
Link newLink = new Link(title, publisher, category,price, quantity, ISBN, day, month, year, userlevel, description); // make new link
if( isEmpty() ) // if empty list,
last = newLink; // newLink <-- last
else
first.previous = newLink; // newLink <-- old first
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
public Link deleteFirst() // delete first link
{                              // (assumes non-empty list)
Link temp = first;
if(first.next == null) // if only one item
last = null; // null <-- last
else
first.next.previous = null; // null <-- old next
first = first.next; // first --> old next
return temp;
public void displayForward()
     System.out.println("first --> last): ");
Link current = first; // start at beginning
while(current != null) // until end of list,
current.displayLink(); //display data
current = current.next; // move to next link
System.out.println("");
//Hoping to hear from you soon.

Similar Messages

  • How do I find the smallest element of a doubly linked list?

    I currently have a doubly link list, each node contains two datafields df1 and df2. I need to find the smallest of df2 contained in the list and swap it with index one - until the list is sorted.
    Any ideas on how to search a doubly linked list for the smallest element would be greatly appreciated, thanks for your help.
    ps: I have found methods for find an element in a list and tried to alter it to find smallest, but my dfs are objects and I am having difficulty with the comparison.
    thanks so much for your time.

    I have given some comments in your other thread and instead of finding the minimum in each scan, you can do "neighbour-swaps". This will sort the list in fewer scans.

  • Travwerse a linked list in a doubly linked list

    I have to traverse a linked list to a doubly linked list and I am not sure how to do that.
    Here is some sample code:
    class linkData {
              dataRecord data;
              linkData next;
              linkData prev;
    linkData head;Should I use something like this:
    if (index < (size >> 1)) {
                     next = header.next;
                     for (nextIndex=0; nextIndex<index; nextIndex++)
                       next = next.next;
                 } else {
                    next = header;
                     for (nextIndex=size; nextIndex>index; nextIndex--)
                         next = next.previous;
                 }

    mindspeed wrote:
    I have to traverse a linked list to a doubly linked list This makes no sense as traverse means to pass or move over or along something. Perhaps you mean translate instead.

  • Sorting a doubly linked list

    Hello people!
    I have problems with sorting a doubly linked list, I have kind of got stuck just looking at the code and don't really know what I'm doing anymore...
    public void sortList()
    int flag = 0;
    DoubleNode temp; //Doubly Linked List Node
    temp = firstNode;
    String tempData;
    while (flag != 1)
    flag = 1;
    String data = (String)temp.element;
    while (temp.next != null)
    int comp = data.compareTo((String)temp.next.element);
    if (comp > 0)
    tempData = (String)temp.element;
    temp.element = temp.next.element;
    data = (String)temp.element;
    temp.next.element = tempData;
    flag = 0;
    else
    temp = temp.next;
    data = (String)temp.element;
    I'm trying to take an easy way around the problem by not swaping nodes but just the data the nodes contain. I'm pretty new to this and my prof. has just gone insane giving us this hardcore assignment.
    is this code even close to be correct?
    is this a good way of tackling the problem?
    thanks a lot! / Dan

    Okay, without going into any great detail about possible issues with the algorithm or code, it's gonna first be necessary to know some more about the DoubleNode class. For example, does it have a next method? If it does, then right off the bat your code will have to be adjusted so that where you have written "temp.next" you actually call the next method (which, if it is parameterless, would be "temp.next()"). As you have it written now, "temp.next" is accessing the "next" attribute of your DoubleNode instance, and I don't think that's what you're intending.
    -dSn

  • Doubly Linked List

    I have a doubly linked list and I wrote two methods, one to insert items at a specified index and one method to remove items at a specified index. I am not 100% sure if I wrote these methods correctly. Well I'm pretty sure I messed something up because I'm having trouble implementing a swap method and I think this is where the problem lies.
       * @param o the object to insert.
       * @param i the index to add the object.
      public void insertAt(Object o, int i) {
        if (i==0) {
          prepend(o);
        else {
          int j= 0;
          Node previous= first;
          Node next= first;
          while (j<i) {
            previous= next;
            next= previous.getNext();
            j++;
          Node insertAt= new Node(o, previous, next);
          previous.setNext(insertAt);
          insertAt.setPrevious(previous);
          insertAt.setNext(next);
          next.setPrevious(insertAt);
        size++;
       * @param i the index of the object to remove.
      public Object removeAt(int i) {
        if (i==0) {
          removeFirst();
          return first.getData();
        else {
          int j= 0;
          Node previous= first;
          Node next= first;
          while (j<i) {
            previous= next;
            next= previous.getNext();
            j++;
          Node temp=next.getNext();
          if (temp.equals(null)) {
            previous.setNext(null);
            last= previous;
            return next.getData();
          previous.setNext(temp);
          temp.setPrevious(previous);
          return next.getData();
      }

    public Object removeAt(int i) {
    if (i==0) {
    removeFirst();
    return first.getData();
    }I can't be sure from the code but the above code looks like a problem: if you remove the node before you get the data, aren't you returning the data from the second node (now the first)?

  • Not to hard for you java types.  Simply creating a doubly linked list.

    How do i go about declaring a doubly linked list and add nodes to it?

    see http://java.sun.com/j2se/1.3/docs/api/java/util/LinkedList.html
    which is implemented as a doubly linked list:
    import java.util.*;
    public class ListTest {
      public static void main(String [] argv) {
        // synchronize if multiple threads are using list
        LinkedList list = Collections.synchronizedList(
          new LinkedList());
        list.addFirst("this");
        list.addLast("is");
        list.addLast("a test");
        ListIterator it = list.iterator(0);
        // with iterator you can walk the list
    }You can then use iterators to walk the list:
    http://java.sun.com/j2se/1.3/docs/api/java/util/ListIterator.html
    Good Luck.

  • Why LinkedList uses doubly linked list and not single link list

    Hi,
    Please help me to understand the concept behind java using doubly linked list for LinkedList and not single link list?
    Edited by: user4933866 on Jun 26, 2012 11:22 AM
    Edited by: user4933866 on Jun 26, 2012 11:25 AM
    Edited by: EJP on 27/06/2012 08:50: corrected title to agree with question

    EJP wrote:
    Could you help me with one real world use case where we need to traverse linklist and arraylist in backward direction other than printing the linklist or arraylist in reverse order. One example is that you might want to use it as a stack. For a very large (+very+ large) stack it would out-perform the Vector-based Stack in the API.The first thing that pops into my head is an undo/redo function for a text editor. Each edit action is dumped onto such a stack. Each time you hit CTRL+Z to undo an action you go back in the stack. Each time you hit CTRL+Y to redo the action you go forward again.

  • Constucting Doubly Linked Lists

    Hi,
    I'm trying to construct a doubly linked list with three nodes. I'm using the following code for the DLL and DLLNode classes:
    public class DLL
         public DLLNode first, last;
         public DLL()
         this.first = null;
         this.last = null;
    public class DLLNode
         protected Object element;
         protected DLLNode pred, succ;
         public DLLNode (Object elem, DLLNode pred, DLLNode succ)
         this.element = elem;
         this.pred = pred;
         this.succ = succ;
    }          and for the driver to create the DLL:
    class CreateDLLNode
    public static void main(String arg[])
         DLL zoo = new DLL();
         zoo.first = new DLLNode("ant", null, new DLLNode("bat", zoo.first, zoo.last));
         zoo.last = new DLLNode("cat",zoo.first.succ, null);
         System.out.println(zoo.first.succ.succ.element);
    }However when I run the above driver I just a null pointer exception when it tried to print the third element (i.e. cat, first's successor's successor) I've figured out that this is because the link pointing from Bat to Cat isn't there, likewise the link from Bat to Ant isn't there (get another exception if I try to print zoo.last.pred.pred). I know there's something wrong with the way I've created the DLL but I don't know what.
    I'd be very grateful for any help anyone can give, thanks!

    When you assign one variable to another (ie: thisVar=thatVar) it does not mean that thisVar will always contain whatever thatVar contains. thisVar only has what thatVar contained at the moment of the assignment.
    thisVar = 1;
    thatVar = 2;
    thisVar = thatVar;
    thatVar = 3;At the end of the above code, thisVar = 2 and thatVar = 3; thisVar does NOT equal 3.
    When you set the bat's successor to zoo.last, zoo.last is null at that moment, so bat's successor will be null. That's the basic idea of where you're going wrong with that part specifically.
    If you're going to go to the trouble of creating an abstract data structure, make the structure itself handle all these things. Give it an add() method with a parameter that accepts the objects. add() can then create a new node and supply the node the information about its previous/next nodes, and then the DLL can also change its own first/last if necessary.
    You should not have to change any of the properties of DLL outside of the DLL. When you do, you start running into problems like the one you have here.
    // assuming add at end of list
    DLL's add(elem)
        last.succ = new node(elem, last, null)
        last = last.succ
    // add in middle
    DLL's add(elem, afterThisNode)
        afterThisNode.succ = new node(elem, afterThisNode, afterThisNode.succ)
        if(afterThisNode.succ.succ)
            afterThisNode.succ.succ.pred = afterThisNodeThen you'll also need versions for where elem is going in position #1 or if it's going to be the first thing in the DLL.
    Another problem with your code too though...
    If you do "thisVar = new object( new object(thisVar))" then the "thisVar" being passed to the inner new object will have the original value of thisVar, not the value which references the outer new object. When your new bat is being made, the pred you're passing to it is also null.

  • Doubly Linked Lists Swap

    I am having a slight problem and I'm not sure what to do here. Basically, I am creating a new class (ExtendedList) that extends a Doubly Linked List class. The method below (SWAP METHOD) that I am creating is supposed to swap the content from the "this" object with the content from the "list" object that is passed in. I am also trying to do this without having to iterate through the content.
    When I step through the code, it seems to swap everything fine as now the "this" object contains the content from the other list and the other list contains the content from the "this" object. My problem though is I have been given a test file to test my code... and it checks the swap function.
    Well, after the swap it goes through a series of checks to make sure that the linked list was swapped correctly. Let's say I have a List1 of 4 items (A,B,C,D) and List2 of 3 items (1,2,3)... well... the swap seemingly works until I do the checks. So List1 goes through the check and it comes to 3... and it performs the following check...
    if (next.prev != link) { errFlag |= NextPrevNotEquLink;  break; }
    And returns the error. Now... I'm not sure what I did wrong here or how to fix my code... (link by the way is my node)... but any suggestions would be GREATLY appreciated!
    =========== SWAP METHOD ===========
    public void swap(ExtendedList list) {
    if (list == null) {
    return;
    ExtendedList temp = new ExtendedList();
    temp.head = this.head;
    temp.tail.prev = this.tail.prev;
    temp.count = this.count;
    this.head = list.head;
    this.tail.prev = list.tail.prev;
    this.tail.prev.next = list.tail;
    this.count = list.count;
    list.head = temp.head;
    list.tail.prev = temp.tail.prev;
    list.tail.prev.next = temp.tail;
    list.count = temp.count;
    =======================================

    =========== SWAP METHOD ===========
    public void swap(ExtendedList list) {
    if (list == null) {
    return;
    ExtendedList temp = new ExtendedList();
    temp.head = this.head;
    temp.tail.prev = this.tail.prev;Shouldn't this be temp.tail=this.tail?
    You have assigned tail to point to the new list, but
    the tail node itself still belong to the old list.When I try to do this... it gives me the error,
    "The variable in an assignment to a blank must be a simple name or a simple name qualified by "this""
    >
    temp.count = this.count;
    this.head = list.head;
    this.tail.prev = list.tail.prev;Same case hereAnd when I do
    this.tail = list.tail;
    It gives me the error:
    "Can't assign a value to a final variable tail";
    >
    this.tail.prev.next = list.tail;
    this.count = list.count;
    list.head = temp.head;
    list.tail.prev = temp.tail.prev;
    list.tail.prev.next = temp.tail;
    list.count = temp.count;
    =======================================

  • Doubly Linked Lists

    Hi there,
    i have just started to use java and was on the topic of doubly linked list and am confused. Is it possible for someone to show me how to implement a doubly linked list????
    Thanx

    if i had to do it, then i'd make a class that's this linked list object, and another class that's node object.
    in list object i'd hold count of nodes (in case someone asks that, so i should not go through list and count all those 1000000 nodes), and would also have reference to first and last node.
    public class KstyleDLList {
    KstyleNode first = null;
    KstyleNode last = null;
    private int count;
    public int getCount() {
      return count;
    public void addNode(KstyleNode node) {
      last.setNext(node); // simply ignore returned value
                          // because if everything is OK, then value returned is null
      next = node;
    public void removeNode(int index) {
      // method body here
    public KstyleNode getFirst() {
      // method body here
    public Kstyle getLast() {
      // method body here
    class KstyleNode {
    private KstyleNode next = null;
    private KstyleNode prev = null;
    public KstyleNode setNext(KstyleNode next) {
      KstyleNode old = this.next;
      this.next = next;
      return old;
    public getNext() {
      // method body here
    public KstyleNode setPrev(KstyleNode prev) {
      // method body here
    public KstyleNode getPrev() {
      // method body here
    }and lots of other methods that i haven't implemented yet.. but this should give you some idea of what you're going to do...

  • Doubly Link List in Java

    How can we write the program for Doubly Link List in java?
    Please give program with detailed explanation.

    You may want to post this on Java forums at:
    http://forum.java.sun.com/forum.jspa?forumID=24
    http://forum.java.sun.com/index.jspa
    I found the following threads that may be of use:
    http://forum.java.sun.com/thread.jspa?forumID=256&threadID=196730
    http://forum.java.sun.com/thread.jspa?forumID=24&threadID=619245
    Also: an example at http://www.sourcecodesworld.com/articles/java/java-data-structures/Doubly_Linked_Lists_with_Enumeration.asp

  • Doubly-linked List Sort has exited due to signal 10 (SIGBUS).

    What does this mean: "Doubly-linked List Sort has exited due to signal 10 (SIGBUS)."
    Thank you.

    Lady777 wrote:
    What does this mean: "Doubly-linked List Sort has exited due to signal 10 (SIGBUS)."
    SIGBUS is a bus error, meaning that your code is attempting to access an invalid address in memory. Most likely your linked list has a bad pointer in it that the code is trying to dereference. I'm not sure if a null pointer would cause a bus error but if your pointer contained garbage - due to not being properly initialized or due to being overwritten by bad data it certainly could.
    Steve

  • Doubly Link List code

    Hi,
    I have got the following code for doubly link list from a book:
    public Link deleteFirst ( ) {
    Link temp=First;
    If(first.next==null)
    last = null;
    else
    first.next.previous=null;
    first=first.next;
    return temp;
    In the above if condition, when we one element in the list, I feel that first should also point to null. If I code it in this way,is it correct?
    if(first.next==null)
    last=null;
    first= null;
    return temp;
    else {
    first.next.previous=null;
    first=first.next;
    return temp;
    Is the modified code correct?
    Zulfi.

    Your modification gives the correct result, but so does the original even though it might not be immediately obvious. Your version is definitely easier to read :)
    Here's the original broken in parts:// temp now points to first
    Link temp=first;
    // if there is only one element
    if (first.next == null) {
        // the last element should be null because it's removed
        last = null;
    } else {
        // else break the link from the second element to the first
        first.next.previous=null;
    // update "first" to the second element in the list.
    // NOTICE: if the list has only one element and it's properly
    // constructed this will set "first" to null!
    first=first.next;
    // return the removed element
    return temp;Actually neither implementations are perfect; they don't check if you are trying to remove the first element of an empty list...

  • A linked list question.

    So, I believe I understand linked lists for the most part, except for two lines....
        boolean add(Transaction item)
            for (Transaction curr = first; curr != null; curr = curr.next)
                if (curr.part_num == item.part_num)
                    return false;
            Transaction newItem = new Transaction();
            newItem.transcode = item.transcode;
            newItem.description = item.description;
            newItem.part_num = item.part_num;
            newItem.quantity = item.quantity;
            newItem.next = first;
            first.next = newItem;
            return true;
        }first is null, so First.next would be the first available space for actual insertion, and this is why it then puts null as newItem.next (the end of the list), and sticks newItem in first.next?
    Im glad I read that pass by value thing earlier at the Java Ranch place...
    Heres my actual question: When newItem.next = first; is called, it just copies null as the next field, but leaves the null in first alone right? And then it takes first.next and makes newItem copy into that field, thus inserting the first real item in the list?
    Please tell me I made that connection right. :-D
    Thanks!!

    Pictures are worth a hundred words with linked lists. Did you even put a pencil and paper next to your computer while doing this program, so that you could draw what is happening when you get confused?
    If first is null, then the for loop is skipped--because first is assigned to curr and the loop only executes when curr is not equal to null.
    So, this happens:
    newItem = new Transaction()
    int Transcode = 0
    String description = null
    int partNumber = 0
    int quantity = 0
    Tranasaction next = nullThen values are assigned to each field:
    newItem
    int Transcode = 10
    String description = "screw"
    int partNumber = 46
    int quantity = 200
    //freeze execution here:
    Tranasaction next = null (what will happen here??)Your assumption was:
    Transaction first = null
    That means first does not refer to a Transaction object. Therefore, first does not have a description member, a quantity member, etc., and this is what things look like just before newItem.next = first; is executed:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ------> nullNow,
    When newItem.next = first; is calledthings change to this:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
          /-------Tranasaction next
    first ------> null That isn't what you want. When you add() a Transaction object to the end of your linked list, it's next member should be null. It's the end of the chain, so there is no next.
    And then it takes first.next and makes newItem copy
    into that field, thus inserting the first real item in the
    list?No. first is null so it does not refer to a Transaction object, and therefore there is no next member variable and consequently no such thing as first.next. You need to understand that null and a Transaction object that has 0 for every member are not the same.
    But suppose for a minute that null and a Transaction object with zeros for every field were the same thing, so that first.next existed. If that was the case, then you could assign newItem to first.next. But, then you would be left with this:
    first
    int Transcode = 0
    String description = null
    int partNumber = 0
    int quantity = 0
    Tranasaction next = newItemWould you want the first Transaction object in your LinkedList to be almost entirely empty?
    Instead, if first is null, you want to make first refer to newItem, i.e. you want to do this:
    newItem ----> Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ----/   nullThen when the add() method ends, since newItem is a local variable, it will be destroyed leaving you with this:
                  Transaction
                  int Transcode = 10
                  String description = "screw"
                  int partNumber = 46
                  int quantity = 200
                  Tranasaction next = null
    first ----/   null

  • Link List question

    This is more of a development question rather than programming I hope its not wrong to post it here. I apologize if I did
    I am developing a Linked List class that handles a list however, there is a potential (in fact almost a certainty) that the nodes could call to itself and cause an endless loop if running through the it. Any suggestion on how to handle such a case ?

    It's kind of hard to say without more details, but the two general approaches that pop to mind are:
    1) Document it. If the user chooses to ignore the docs, they get bad--posisbly undefined--behavior, and that's their problem.
    2) On every relevant operation, do a search for cycles. Keep track of which nodes you've touched so far. Since the size of the list (and hence the length of a cycle) is theoretically unbounded, and searching every possible path for cycles in a large or complex list (which sounds more like a graph than a list) can take mucho time and/or memory, you'll have to set an upper bound on how deep you'll search. If there's a cycle whose path length is longer than this depth, then you're back to #1 anyway.

Maybe you are looking for

  • How to save the data from alv output

    My ALV output is editable one.I want that user can edit the output and  save the output details into database.How to do it? Moderator Message: Basic Question. This site is not an alternative for your Consultancy work. Put some effort of your own befo

  • How do I rotate view 90 degrees in digital editions?

    how do I rotate view 90 degrees in digital editions?

  • I want to buy Adobe Acrobat XI Pro full version... Limited access vs. full access?

    I want to buy Adobe Acrobat XI Pro full version, but I don't know what the difference is between limited access to online services offered by the full version and the full access that's offered by the month-to-month version. In other words, what woul

  • Evaluation of Solaris 8 - Internet Dial Up

    I'm looking to load Solaris 8 onto a new development box which will run Oracle and associated tools. I am trying to find out if Solaris has a function similar to Windows Dial Up Netwokring or if Solaris makes other arangements for Internet connection

  • HT4527 Transferring Itunes to Mac without duplicating

    I've had my Mac for about a year and now decided to import all of my cd's into itunes on my HP computer because I don't have a cd drive on my Macbook air. What is the best way to move my itunes with all of the newly imported music from my HP computer