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.

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.

  • 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 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.

  • 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...

  • How to print the contents of doubly-Linked List

    Hi
    I have a DLList consists of header , trailer and 10 linked nodes in between
    Is there a simple way to print the contents ie "the elements"
    of the list
    thanks

    In general you should write an iterator for every linked data structure for fast traversal. I'm guessing you're writing your own DLL for an assignment because one normally uses the LinkedList structure that is included in the api. Anyway, here is an example of how the iterator is implemented for a double linked list:
    http://www.theparticle.com/_javadata2.html#Doubly_Linked_Lists_with_Enumeration

  • Help with creating a doubly linked list

    So I have been working with this file our teacher gave us, which is his own "list" ADT which I posted below (with out the comments so it doesn't stretch the page for ever)
    My question is, I cant really creat a DLL from this because I have nothing for the head, no previous or next or any of that...So could some one help me get off to the right start? Some of my class mates were like "create a SLL and then reverse it" well thats all fine and dandy but how?
    A couple other student said "With this DLL i only had to write two lines for each method to implement the list"...Can that be done? Theres NO documentation any where on a DLL for java, and the linkedList in the java api...I dont think that's a DLL...
    I SERIOUSLY need a nudge in the right direction....
    package assignment.four.utilities;
    import java.io.Serializable;
    public interface List<E> extends Serializable
         public int size ();
         public void clear ();
         public boolean add (int index, E toAdd) throws NullPointerException,
                                                                     IndexOutOfBoundsException;
         public boolean add (E toAdd) throws NullPointerException;
         public boolean addAll (List<? extends E> toAdd) throws NullPointerException;
         public E get (int index) throws IndexOutOfBoundsException;
         public E remove (int index) throws IndexOutOfBoundsException;
         public E remove (E toRemove) throws NullPointerException;
         public E set (int index, E toChange) throws NullPointerException,
                                                                IndexOutOfBoundsException;
         public boolean isEmpty ();
         public boolean contains (E toFind) throws NullPointerException;
         public E [] toArray (E [] toHold) throws NullPointerException;
         public E [] toArray ();
         public Iterator<E> iterator ();     
    }Again with my statement. Using that List ADT HOW do you even get started in the right direction to creating a DLL? I can use this to create an array list but i dont think i can for a dll?
    Edited by: user8974754 on Nov 20, 2010 8:00 PM

    user8974754 wrote:
    Ok thats fine and dandy but we never learned how to make a DLL we learned last semester how to make a SLL and I kinda get that but again with the So, you know how to make an SLL? Then I would suggest starting with that. For instance, you know how to define a Node or Element or whatever-you-want-to-call-it class that holds Data and Next? Start with that, and see if you can work out how to add a Previous.
    "there's nothing on DLL's" except for the same line over and over "They go backwards and forwards" and Im sorry but that doesn't cut it......So, [url http://www.youtube.com/watch?v=Ijae2WHdc9I]you know how to count blocks, but you don't know how to count oranges? That is, you know how to make forward links in a list, but not backward links? Really?
    Is there any examples of Java Dlls implementing lists and bla?I'm sure there are plenty, and I'm sure your google works as well as mine.
    like we cant implement any thing else as far as I know, it can only be this list....When I said you need to implement the various pieces, I meant in the normal English sense of the word, not in the Java keyword sense. Implementing a Node in the general sense is part of "implements List" in the Java keyword sense.
    I know the asking for a sample implementation might be considered cheating in some peoples books Yup.
    but i learn best from examples, explanations and what not...There's a world of difference between an example of a different use of the concepts that you're trying to learn and just doing your work for you. Whatever concepts this lesson is teaching that are being tested and reinforced by this homework, you can find plenty of examples without somebody providing a DLL implementation for you.
    Edited by: Am I still jverd? on Nov 20, 2010 9:05 PM

Maybe you are looking for

  • Swithch phone numbers on phones under same contract

    I have 4 phone on my account. I want to switch the numbers on 2 of the phones. (i am giving it to my son). I need to keep my number for professional reasons. How do i go about doing this?

  • How do I move my iPhoto files to an external harddrive?

    Hi there I only recently moved to Apple from Windows and am struggling to move my iPhoto files to an external harddrive, despite there being some quite old discussions on this on these discussion boards. My late 2013 32GB Macbook Pro Retina is curren

  • How to combine 2 xmls in a single message ?

    Hi Guys, I have a requirement where i need to do the HTTP post and the xml request should be as below The AddressValidationRequest message consists of two complete XML documents. The first document is an AccessRequest. It is immediately followed by a

  • Pen Tool + Vector Mask behaviors

    I've discovered some inconsistancies with the Pen Tool and Vector Mask behaviors on the Mac, using Snow Leopard 10.6.8 on a Mac Pro Tower. 1. When a completed Path is converted to a Vector Layer Mask, the Path Layer remains active, The new Vector Lay

  • Intel SSD in MacBook Pro

    Hi everyone, I have a Macbook Pro 15, mid-2009. I put a SSD in it. However, it's getting slow gradually. My question is how to restore the Intel SSD performance like brand-new. Please as specific as possible, thank you.