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

Similar Messages

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

  • 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)?

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

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

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

  • Help with linked list code.

    Here's a basic linked list code that I need help on.
    What I need assistance with:
    1. How would I rewrite and delete words/phrases in the file IO section of my code?
    2. How would I make the code recognize all the words on each line of the linked list? Only the words on the first line of the file go into the linked list.
    import java.util.LinkedList;
    import java.io.*;
    import javax.swing.JOptionPane;
    public class LinkedLists {
        public static void delete (LinkedList test)
            int a = Integer.parseInt(JOptionPane.showInputDialog(null,
            "Enter a position to delete"));
            test.remove(a - 1);
            System.out.print(test);
        public static void add (LinkedList test)
            String user = JOptionPane.showInputDialog(null, "What to input?");
            int b = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "What position to enter it in?"));
            test.add(b - 1, user);
            System.out.print(test);
        public static void fileRead(LinkedList test) throws IOException
            BufferedReader fileIn;
            String text;
            fileIn = new BufferedReader(new FileReader("z:/data.txt"));
            text = fileIn.readLine();
            fileIn.close();
            int b = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "What position to enter it in?"));
            test.add(b - 1, text);
            System.out.print(test);
        public static void fileWrite(LinkedList test) throws IOException
            PrintWriter fileOut;
            fileOut = new PrintWriter(new FileWriter("z:/data.txt",true));
            String user = JOptionPane.showInputDialog(null, "What to input?");
            fileOut.println(user);
            fileOut.close();
            fileRead(test);
        public static void main(String[] args)  {
            LinkedList test = new LinkedList();
            test.addLast("Fly");
            test.addLast("money");
            test.addLast("awesome");
            test.addLast("woot");
            test.addLast("yay");
            System.out.print(test);
            System.out.println();
            int x = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "Enter \n1 to Delete \n2 to Add \n3 to read data from file \n4 to write into the file and add to list"));
            if (x == 1) {
                delete(test);
            if (x == 2) {
                add(test);
            if (x == 3) {
                try {
                    fileRead(test);
                } catch (IOException e) {
                    e.printStackTrace();
            if(x==4)
                try {
                    fileWrite(test);
                } catch (IOException e) {
                    e.printStackTrace();
    }Edited by: Johnston on Sep 16, 2007 1:13 AM

    Hi,
    Johnston wrote:
    1. How would I rewrite and delete words/phrases in the file IO section of my code?You want to replace or remove in/from the file?
    First you have to define a file format. This is not a Java technical term, but a thing what you have to keep in mind. Simplest format is:
    - each ListItem is one line in the file closed with newline.
    Now you can read the file line by line and store the lines in a memory structure (LinkedList for ex ;-)). Then replace or remove the designated elements an write the file new by iterate over the list and write each item as line in the file.
    Johnston wrote:
    2. How would I make the code recognize all the words on each line of the linked list? Only the words on the first line of the file go into the linked list.You have to read the file line by line and then add each line as item of the list.
    Examples for reading/writing textfiles:
    http://www.exampledepot.com/egs/java.io/pkg.html#Reading%20and%20Writing
    Btw: Deal with Generics (see http://java.sun.com/docs/books/tutorial/extra/generics/index.html) an use this knowledge to declate your List better.
    greetings
    Axel

  • 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

  • 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

Maybe you are looking for

  • How can i connect my Imac sound to my stereo receiver speakers and not disconnect the computer's speakers?

    I find lots of confusing answers re how to connect my Imac to my stereo receiver, and I aldso want to avoid cutting of the Imac's speakers entirely when the sound goes to the stereo receiver and thsu to the larger speakers. Is there a way to switch b

  • HR_IN_CHG_INR_WRDS

    hi experts , i have the following code sample. TABLES: mseg. TYPES: BEGIN OF st_tab ,         matnr LIKE mseg-matnr,         werks LIKE mseg-werks,         waers LIKE mseg-waers,         dmbtr LIKE mseg-dmbtr,       END OF st_tab. DATA: itab TYPE STA

  • Changing PO default currency using BADI

    Hi all, I received a requirement to use the same currency in PO than was chosen in PR. For example, a PO from PR created in USD should be in USD a PO from PR created in EUR should be in EUR I am trying to do this using BADI ME_PROCESS_PO_CUST but des

  • Resource Bundle question

    Can I keep HTML format in a resource bundle -properties file? Anybody has expirience?

  • My Canon EOS Rebel T4i will not operate with a new battery. What could cause this problem?

    While take pictures with my Canon EOS Rebel T4i camera it died.  I assumed it was a dead battery.  Upon charging the battery it would take just a few pictures and die again.  I purchased a new cannon battery and fully charged it and now the camera wi