Sorting (doubly linked list)

Hi, I want to sort regarding to element "marke", I wrote this code, but after executing it I loose one element and it does not sort anything. What am I doing wrong?
    public void sort() {
         Automobilis elem = new Automobilis();
         elem =  pirmas;
         Automobilis elemX = new Automobilis();
         Automobilis elemY = new Automobilis();
         elemY = pirmas;
         Automobilis elemNew = new Automobilis();
            String rasymui;
         while(elem != null && elem.sekantis != null) {
              elemX = pirmas;
              while(elemX.sekantis != null && elemX != elemY) {
                   if (elemX.marke.compareTo(elemX.sekantis.marke) > 0) {
                        elemNew.marke = elemX.marke;
                        elemNew.metai = elemX.metai;
                        elemNew.rida = elemX.rida;
                        elemNew.kaina = elemX.kaina;
                        elemX.marke = elemX.sekantis.marke;
                        elemX.metai = elemX.sekantis.metai;
                        elemX.rida = elemX.sekantis.rida;
                        elemX.kaina = elemX.sekantis.kaina;
                        elemX.sekantis.marke = elemNew.marke;
                        elemX.sekantis.metai  = elemNew.metai;
                        elemX.sekantis.rida = elemNew.rida;
                        elemX.sekantis.kaina = elemNew.kaina;
                   elemY = elemX;
                   elemX = elemX.sekantis;
             elem = elem.sekantis;
                   rasymui = elem.gautiMarke() + ",\t" + elem.gautiMetus() + ",\t" + elem.gautiRida() + ",\t" + elem.gautiKaina();
                   System.out.println(rasymui);
               }In data file I have this:
Opel Calibra, 1991, 250000, 5000
Ford Escort,  1994, 185000, 4500
BMW 535,      1999, 405000, 7500
ZAZ 626,      1975, 45000,  500
MB SLK 200, 2001, 149000, 57000After sorting the results are:
ZAZ 626,           1975,   45000.0,        500.0
BMW 535,         1999,   405000.0,       7500.0
Ford Escort,     1994,   185000.0,       4500.0
Opel Calibra,   1991,   250000.0,       5000.0

I'm a little confused about something here:
elemY = pirmas;
while(elem != null && elem.sekantis != null) {
          elemX = pirmas;
while(elemX.sekantis != null && elemX != elemY) {
...How is it that you ever get into this internal loop if you set elemY and elemX equal to the same thing? I don't actually see what the purpose of elemY is at all.
Just in general though, you shouldn't need to create new objects in a sort, and you shouldn't be moving data from one node to another. The only thing you want to change is the next pointer (sekantis?) If you want to swap two elements, all you have to do is:
elem1.next = elem2.next;
elem2.next = elem1;

Similar Messages

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

  • 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 singly linked list with minimum time complexity

    Hi ...
    anyone could tell me how can i sort singly linked list with minimum time complexity .... ????
    Regards...

    By MergeSort or QuickSort O(n log n). But then you
    have to first extract the objects in the list,sort
    them, then rebuild the list. But it will still bealot
    faster than by keeping the list linked.Technically, I believe insertion sort is marginally
    faster for small n ( <20 or so).Woohoo! So for 20 out of the possible 2147483648 array
    sizes Insetion is faster!
    Unfortunately, checking for that case probably wastes
    all the time you get from using the faster sort...
    That would depend on the actual distribution off array sizes. So it's an engineering decision.
    Sylvia.

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

Maybe you are looking for

  • How to delete the heapdump, Javacore and Ariview files

    Hi all, i got the problem with the heapdump and javacore files the problem is /usr directory we assigned space of 17 GB, after some days it got filled up, so we deleted the heapdump, javacore and arciviews in /usr/sap/SID/<instance>/j2ee/cluster/serv

  • My MBP doesn't remember my Time Capsule wireless network when waking from sleep

    My MBP (OS 10.5.8) doesn't remember my Time Capsule wireless network when waking from sleep.  Thus, every time my MBP wakes from sleep, I need to select the Airport icon in the upper menu bar, select "Join other network", enter SSID and password.  Th

  • Any 3rd Party Application(s) to export to tape?

    Heya guys. Hope production has been treating you all well. I'm kind of in a jam here where for some reason both my sony dv decks have stopped working via firewire. I currently need a third party application(if one exists) that can export a ProRes fil

  • Problem with hp wi-fi mobile mouse

    can i use Hp wi-fi mobile mouse with ubuntu? thank you

  • Variable and Xquery

    While configuring pipeline... In stage I added first action which assigns value to AccountReq variable i.e. fn:data($body/acc:getAccountInfo/string) is assigned to AccountReq AccountReq variable holds the value <get:GetAccountDetailsRequest xmlns:get