Sorting into Linked Lists

What I want to do is make a Linked List that has options.
1. Allows Duplicates & Non Sorted
2. Allows Duplicates & Sorted Alphabetically
3. Allows Duplicates & Sorted Reverse Alphabetically
4. Doesn't Allow Duplicates & Non Sorted
5. Doesn't Allow Duplicates & Sorted Alphabetically
6. Doesn't Allow Duplicates & Sorted Reverse Alphabetically
sortOrder and duplicate are my global variables controlling those two options.
Reverse alphabetical and alphabetical will just be opposites.
I've got the duplicates or non duplicates part working as well as non-sorted part.
    public void add(Object obj){
    // post: appends the specified element to the end of this list.
        Node temp = new Node(obj);
        Node current = head;
        Node hold = head;
        // starting at the head node, crawl to the end of the list
        //Takes care of duplicates
        if (!duplicate) {
            if (lookup(obj)) {
            return;
        System.out.println("OBJECT: " + obj.toString()); // See what I am passing
        if (sortOrder==0) { //non-sorted
            while(current.getNextNode() != null) {
                current = current.getNextNode();
        // the last node's "next" reference set to our new node
            current.setNext(temp);
        if (sortOrder<0) { // decreasing
            while(current.getNextNode() != null) {
                current = current.getNextNode();
                System.out.println("CURRENT: " + current.getData().toString()); //Where I am sitting in the list
                System.out.println("IF STATEMENT: "+ obj.toString().compareTo(current.getData().toString())); // Where the object sits alphabetically to current
                    if(obj.toString().compareTo(current.getData().toString())>0) {
                        hold.setNext(temp);
                        temp.setNext(current);
                        System.out.println("Object is closer to z Alphabetically");
                        return;
        // the last node's "next" reference set to our new node
/*    if (sortOrder>0) { // increasing
        while(current.getNextNode() != null) {
            current = current.getNextNode();
            System.out.println("CURRENT: " + current.getData().toString());
            if (obj.toString().compareTo(current.getData().toString())<0){
    // the last node's "next" reference set to our new node
                temp.setNext(current.getNextNode());
                current.setNext(temp);
                return;
}

humer015 wrote:
What I want to do is make a Linked List that has options.
1. Allows Duplicates & Non Sorted
2. Allows Duplicates & Sorted Alphabetically
3. Allows Duplicates & Sorted Reverse Alphabetically
4. Doesn't Allow Duplicates & Non Sorted
5. Doesn't Allow Duplicates & Sorted Alphabetically
6. Doesn't Allow Duplicates & Sorted Reverse AlphabeticallyI'd set up 4 separate collections with the correct characteristics (6 if you think you need to keep the 'reverse order' versions separately). Remember, having 6 lists doesn't mean 6 sets of data; just 6 arrangements.
sortOrder and duplicate are my global variables controlling those two options.Sounds like an implementation decision before its time to me, unless it's dictated by programs that you have no control over. Get your lists working and then decide how you want to implement your system parameters.
HIH
Winston

Similar Messages

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

  • Sorting a Linked list.

    Hi, I'm not much good at the coding and require some help, i looked through past posts and haven't found much help.
    public class Queue2
    private node start,last;
    private static class node
    private int nPriority;
    private String todo;
    private node link;
    public Queue2()
    start = null; last = null;
    public void add(int key, String todo)
    node temp = new node();
    temp.nPriority = key;
    temp.todo = todo;
    temp.link = null;
    if (start != null)
    last.link = temp;
    last = temp;
    else
    start = temp;
    last = temp;
    public int remove()
    if (last != start)
    int x = start.nPriority;
    start = start.link;
    return x;
    else if (start != null)
    int x = start.nPriority;
    start=null; last =null;
    return x;
    else return -1;
    public void print()
    node curr = start;
    if (curr == null)
    System.out.println("No Tasks");
    else
    node temp = start;
    System.out.println("List of tasks todo :-");
    while (temp !=null)
    System.out.print(temp.nPriority + " : " + temp.todo + "\n");
    temp = temp.link;
    System.out.println();
    Theres my code atm, I guess I need to either alter the add() method to put new objects into the list in order or to add a sort() method.
    I need the list to be output in order of the lowest int in nPriority first.
    Any help will be very much appreciated.

    First of all, you post your code the wring way so it is hard to read. Use tags. (http://forum.java.sun.com/faq.jsp#format)
    Second, I think you lack curly braces in the 'else' in the end.
    Third, as far as I can see your whole logic is very far from the mark. (But that may be just me being unable to grasp the way you try to do it. (Which again may be caused by #1 above)) Here's some rough (pseudo)code for a sorted insert: void sortedInsert(Node newNode) {
        //special case, insert in beginning:
        if (newNode.pri < list.first.pri) {
            newNode.next = list.first;
            list.first = newNode;
        else {
            Node previous = null;
            Node current = list.first;
            while (current.next != null) {
                previous = current;
                current = current.next;
                if (newNode.pri < current.pri) {
                    //insert before current
                    previous.next = newNode;
                    newNode.next = current;
                    return;
            //other special case: Insert at the end
            current.next = newNode;

  • Sorting My Linked List

    Alright, here's the problem. I have my linked list, either imported from a text file or inputted by the user. Now, I need to sort it by the date and the time strings... Yet, every time I do I get an NullPointException. Can anyone help? Here's my code for the list:
    public class ListReferenceBased implements ListInterface{
         //references to the linked list items
         private Node head;
         private int numItems; //number of items that exist in list
         //Default Constructor
         //sets both items to null
         public ListReferenceBased(){
              numItems = 0;
              head = null;
         //if the numItems in the list is empty
         //returns true.
         public boolean isEmpty(){     
              return numItems == 0;
         // returns numItems, aka the size of the list
         public int size(){
              return numItems;
         //finds a node by setting a node to the 'head'
         // and loops through to the index 'resetting'
         // curr to the 'next' node.
         private Node find(int index){
              Node curr = head;
              for( int skip = 1; skip < index; skip++){
                   curr = curr.getNext();
              return curr;
         public Object get(int index)
              throws ListIndexOutOfBoundsException{
              //catches if list does not reach the index given
              //loops through the index
              if(index >= 1 && index <= numItems){
              //sets curr to the index through find()
              Node curr = find(index);
              //sets dataitem to the current node
              Object dataItem = curr.getItem();
              return dataItem;
              }else{
              throw new ListIndexOutOfBoundsException("The List index is out of bounds on get");
         public void add(int index, Object item)
              throws ListIndexOutOfBoundsException{
              //checks to make sure there are no nodes yet
              //if there are inserts them in the list
              //by moving
              if(index >=1&& index<= numItems+1){
                   if(index==1){
                        // if no list exists
                        //creates a new node and sets it to head
                        Node newNode = new Node(item, head);
                        head = newNode;
                   }else{
                             //inserts the node at the index
                             //by finding it first
                             Node prev = find(index-1);
                   //creates a new node by placing the Object item
                   //and the 'new prev' node into a node
                   //'deleting' the old 'bonds'
                   Node newNode = new Node(item, prev.getNext());
                   rev.setNext(newNode);
                        //increments number of items in list
                        numItems++;
              }else{     
                        throw new ListIndexOutOfBoundsException("List index out of bounds");
         public void remove(int index)
              throws ListIndexOutOfBoundsException{
              //catches the list if it doesn't exist
              //checks to make sure list exists
              if(index>=1&& index<= numItems){
                   //if only the head exists
                   //calls next node else moves
                   //the node away and moves the prev
                   //on up.
                   if(index==1){
                        head = head.getNext();
                   }else{
                        Node prev = find(index-1);
                        Node curr = prev.getNext();
                        prev.setNext(curr.getNext());
                   //decreases the number of items in list
                   numItems--;
              }else{
         throw new ListIndexOutOfBoundsException("List index out of bounds");
         //sets the numItem to null telling the list it
         //does not exist
         public void removeAll(){
              head = null;
              numItems=0;
              

    Yeah, unfortunately, I had to design my own linked list for my assignment (that's taken almost 40+ hours). So, now every alogrithm I've tried to write seems to give me a null pointer, for example this one
    public void sort(){
              //loop through all existing nodes
              for(Node curr = head; curr != null; curr = curr.getNext()){
                   //parse the string of the current node
                   //to a string value
                   Node current = curr.getNext();
                   Node next = current.getNext();
                   Node temp;
                   String thisline = current.getItem().toString();
                   System.out.println(thisline);
                   StringTokenizer parser = new StringTokenizer ( thisline, "\t" );
                   String thisdate = parser.nextToken();
                   String thistime = parser.nextToken();
                   String thisline2 = next.getItem().toString();
                   System.out.println(thisline2);
                   StringTokenizer parser2 = new StringTokenizer ( thisline2, "\t" );
                   String thisdate2 = parser.nextToken();
                   String thistime2 = parser.nextToken();
                   //compares the dates of next in list
                   if(thisdate.compareTo(thisdate2)==1){
                        next.setNext(current);
                        current.setNext(next.getNext());
                        printList();
                        //if dates equal, compare the times
                   //if equal move to new position
                        //delete old position
    }Pretty much I believe moving the positions is causing the problems after the first run around. Any suggestions?

  • Bubble Sort in Linked List

    so, everything works through the first iteration (don't know if this is an appropriate term for linked lists, but we just learned arrays) but then it stops. I thought that telling it to continue until position.next != null and increasing the position after every iteration would work but I think I have coded something incorrectly / am not taking something into consideration. I would be greatly obliged if you can offer any advice!
    Thanks,
    Hunter
           public void bubbleSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next != null)
             {  current = position.next;
                        previous = position;
                a = current.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      Node temp = a.next;
                      a.next = previous.next;
                      previous.next = current.next;
                      current.next = temp;
                                  previous = a;
                                  a = temp;
                    else
                                  a = a.next;
                      current = current.next;
                                  previous = previous.next;
                 position = position.next;
             head = head.next;

    First, thanks for the response! I have been trying println statements and really don't understand the problem. I have also gone through line-by-line and drawn out what I think is supposed to happen and still can't seem to fully figure out what I am doing wrong. Here is the full code, this might help with the 'definition of my list'.
        public class LinkedList
          public Node head;
           public LinkedList(int length)
             head = null;
             for (int i = 0; i < length; i ++)
                insert(i);
           public LinkedList()
             head = null;
           public void clear()
             head = null;
           public void insert(int n)
             Node current = new Node(n);
             current.next = head;
             head = current;
           public void insert(Node n, int index)
             Node previous, current;
             Node nnode = new Node(-10);
             nnode.next = head;
             previous = nnode;
             current = head;
             while (current != null && index > 0)
                current = current.next;
                previous = previous.next;
                index --;
             if (previous == nnode)
                n.next = head;
                head = n;
             else
                previous.next = n;
                n.next = current;
       //Delete the node at the zero-based index.
           public void delete(int index)
             int current;
             Node currentnode = head;
             for (current = index; current > 1; current --)
                currentnode = currentnode.next;
             if (currentnode == head)
                head = head.next;
             else
                currentnode.next = currentnode.next.next;
           public Node getNode(int index)
             Node nnode = new Node(-10);
             nnode.next = head;
             Node current = head;
             while(current.next != null && index > 0)
             {     current = current.next;
                index --;
             return current;
           public int getVal(int index)
             int current;
             Node currentnode = head;
             for (current = index; current > 0; current --)
                currentnode = currentnode.next;
          //currentnode should point to the node whose value we want.
             return currentnode.getVal();
           public void print()
             System.out.println();
             head.print();
           private void swap(Node pa, Node a, Node pb, Node b)
             Node temp = b.next;
             pa.next = b;
             if (a.next != b)
                b.next = a.next;
                pb.next = a;
             else
                b.next = a;
             a.next = temp;
           public void selectionSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next  != null)
                current = previous = position.next;
                a = position.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      current = a;
                      while(previous.next != current)
                         previous = previous.next;
                   a = a.next;
                if (current != previous)
                   Node t = position.next;
                   swap(position, t, previous, current);
             //System.out.println("****************");
             //head.print();
                position = position.next;
             head = head.next; //to lose the initial node.
          //System.out.println("end of sorting, head.print is");
          //head.print();
           public void bubbleSort()
             Node current, a, previous, position;
             position = new Node(0);
             position.next = head;
             head = position;
             while (position.next != null)
             {  current = position.next;
              previous = position;
                a = current.next;
                while(a != null)
                   if (a.getVal() < current.getVal())
                      Node temp = a.next;
                      a.next = previous.next;
                      previous.next = current.next;
                      current.next = temp;
         previous = a;
         a = temp;
                    else
                    a = a.next;
                    current = current.next;
         previous = previous.next;
                 position = position.next;
             head = head.next;
          }

  • Selection Sort using Linked Lists

    As the subject says, I'm trying to implement a selection sort method on a linked list structure. I've already created a bubble sort, but I can't seem to get this method to work correctly. The Node and LinkedList classes were written by me, and I know they work correctly (because of the other methods work right).
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                boolean exchangeMade;
                while (pointer.getNext().getNext() != null) {
                    current = pointer;
                    exchangeMade = false;
                    iterationsOUTER++;
                    while (current.getNext() != null && !exchangeMade) {
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            exchangeMade = true;
                            iterationsINNER++;
                            swaps++;
                            comparisons++;
                        current = current.getNext();
                    pointer = pointer.getNext();
              //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }For instance, if I run this bit of code...
    LinkedList list = new LinkedList();
            list.insert(5);
            list.insert(29);
            list.insert(2);
            list.insert(1);
            list.insert(13);
            list.insert(8);
            list.insert(30);
            list.insert(3);
            sort.selectionSort(list);
            list.print();The output is...
    1
    8
    13
    3
    2
    29
    30
    5
    Anyone have any idea what is going wrong, or is anymore information needed?
    PS: I also need to create a insertion sort method with this, and I've been told I need to reverse the list for the insertion sort to work correctly. Any tips on how to implement this method too? :)

    I've changed it up a bit, and it works, but is this still a bubble sort? I've tried uncommenting that section that keeps track of the iterations and such, but I know they can't be right. Does this look correct? I basically just removed that boolean check...
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                while (pointer.getNext() != null) {
                    current = pointer;
                    iterationsOUTER++;
                    while (current.getNext() != null) {
                        comparisons++;
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            iterationsINNER++;
                            swaps++;
                        current = current.getNext();
                    pointer = pointer.getNext();
                System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }And no, I tried and I don't get a NullPointerException if I have a list of 2.
    Edited by: birdboy30 on Dec 3, 2007 7:23 PM

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

  • Gather information from form fields, sort into links for searching

    I have a PDF Acrobat form that I email to about 100 people, they return the completed forms to me and I put all the forms together into a single PDF.This removes the form fields, but leaves the form information that was filled out.
    I need to set up an easy way for people to navigate and search the forms by several criteria: a person's name, their country of origin, company name, and so forth. Other than manually creating links for each of these search criteria, is there a more efficient way?

    You can export the data form the PDF using the FormDataIntegration service.
    Once you have the data in xml format, you can use a setValue and concatenate the value of the two nodes you're interested in.
    Jasmin

  • Sorted Double Linked List.

    public class DLinkedList {
    class Node {
    String data;
    Node next = null;
    Node prev = null;
    public Node(String o, Node n, Node p){
    data = o;
    next = n;
    prev = p;
    private int max;
    private Node head;
    private Node current = null;
    public DLinkedList(int max_size) {
    head = null;
    current = null;
    max = max_size;
    public boolean isEmpty() {
    public void insert(String o) {
    Node n;
    while (current != null && o.compareToIgnoreCase(current.data) > 0)
    current.prev = current;
    current = current.next;
    if (current.prev == null)
    // First Item in List
    n = new Node(o, current, null);
    else
    current.prev.next = new Node(o, current, current.prev);
    I am working on the insert and keep getting a null pointer exception. Can someone point me in the right direction.
    Thanks

    if (current.prev == null)
      // First Item in List
      n = new Node(o, current, null);
    }This code right here will cause a NullPointerException if current is still null, which is one of the possible exit conditions in your loop.

  • N^2 log(n) for Collections.sort() on a linked list in place?

    So, I was looking over the Java API regarding Collections.sort() on linked lists, and it says it dumps linked lists into an array so that it can call merge sort. Because, otherwise, sorting a linked list in place would lead to a complexity of O(n^2 log n) ... can someone explain how this happens?

    corlettk wrote:
    uj,
    ... there are other sorting methods for linked lists with an O(N*N) complexity.Please, what are those algorithms? I'm guesing they're variants off insertion sort, coz an insertion is O(1) in a linked list [and expensive in array]... Am I warm?You don't have to change the structure of a linked list to sort it. You can use an ordinary Bubblesort. (The list is repeatedly scanned. In each scan adjacent elements are compared and if they're in wrong order they're swapped. When one scan of the list passes without any swaps the list is sorted). This is an O(N*N) algoritm.
    What I mean is it's possible to sort a list with O(N*N) complexity. It doesn't have to be O(N*N*logN) as the Java documentation kind of suggests. In fact I wouldn't be surprised if there were special O(N*logN) algoritms available also for lists but I don't know really. In any case Java uses none of them.

  • Comparable linked list sorting

    i have been trying to find a way to sort a link listed. After some reading i found out that it is probably best to use collections.sort(list). I think i understand how to implement it , i need to declare a compareto and equals method. However, most of the reading i have done shows how to create a collection from a linked list and add items to the collection and sort them, however it doesn show how to copy this sorted collection back inot a linked list. I need to remove items and add items to the sorted linked list. Is it possible to create a linked list, sort it using the collection sort and return the sorted linked list? I have looked in the api's but got confused!!

    You don't need to copy anything.
    List list = new LinkedList(); // or ArrayList
    // list.add stuff
    Collections.sort(list); Assuming whatever you added to the list implements Comarable, the list is now sorted.

  • Sort Linked List...

    I need help sorting a linked list.
    So far, in my sort method I have...
    public LinkedList sort();
    LinkedList newList = new LinkedList();
    Node ref;
    Node temp = new Node(head.getempID(); head.getempLast(), head.getempFirst(); head.getempDept(), head.getempSalary());
    for(ref = head; ref != null; ref.getNext());
    if(ref.getempID() <= temp.getEmpID());
    temp = (ref.getempID(), ref.getempLast(), ref.getempFirst(), ref.getempDept(), ref.getempSalary());
    newList.insert(temp); //???????
    return newList();
    // As you can tell, each one of my node's consists of an employee's id number, last name, first name, department, and salary...I need to sort the linked list by the employee's ID number. I can not figure out how to swap nodes though. PLEASE HELP A KID OUT!!!

    I was worng, my last data structure lecture today(I hope).
          |       |     |       |     |       |     |       |         |       |
    head->| Node1 |---->| Node2 |---->| Node3 |---->| Node4 |---etc-->| NodeN |->null
          |       |     |       |     |       |     |       |         |       |
    Q: How do you swap node2 with node3?
    A: Think about it!  Look at a picture if thats what you need. Draw the lines of reference to figure it out.
      1. Where does node1.next need to point to, how about node2.next, or node3.next?
      3. How do you change these without losing a node, are you going to need a temp?
      4. What about special case(switching node1 and node2)?
    This is simple problem solving skills.  I assume you have built the list yourself,
    so you have the basic knowledge base needed.

  • Addition in a linked list

    Hi,
    I want to add numbers in a linked list. For example when i pass in the string 123456789, i reverse it so that it appears as 987654321 in the linked list. If i add this to the string 954 which appears as 459 in the linked list, i am supposed to get 123457743 but i get 1743. How do i rectify this from my code.
    import java.util.LinkedList;
    import java.util.ListIterator;
    public class LargeInteger {
    /** Constructs a new LargeInteger object from the specified String.
    * The String parameter will contain the digits comprising the number
    * to be represented by this LargeInteger object. The number may be
    * either positive or negative, so be sure to check for a sign.
    * You should throw an IllegalArgumentException if the string which is
    * passed in does not contain a valid number. An invalid String would
    * be one which contains any character other than a digit (however the
    * first character may be a negative sign).
    * @param value A String representing the number to be represented.
    &nbs! p; * @throws IllegalArgumentException This exception is thrown if the
    * parameter doesn't contain a valid number.
    LinkedList digits = new LinkedList();
    public LargeInteger(String value) throws IllegalArgumentException {
    //Declare variables
    boolean neg = false;
    int num = 0;
    int start = 0;
    char ch = ' ';
    Integer tempObj = new Integer(num);
    //If the first character is not a - sign or it is less than the character 0
    //or it is greater than the character zero, then throw
    //IllegalArgumentException
    //else add digits into linked list as integers
    if(value.startsWith("-")) {
    neg = true;
    start = 1;
    } else if ( !Character.isDigit(value.charAt(0)) ) {
    throw new IllegalArgumentException();
    for (int j = value.length()-1; j >= start; j--) {
    ch = value.charAt(j);
    if (Character.isDigit(ch)) {
    num = Character.getNumericValue(ch);
    tempObj = new Integer(num);
    digits.add(tempObj);
    } else {
    throw new IllegalArgumentException();
    } // end Constructor
    public static void main(String[] args) {
    LargeInteger a = new LargeInteger("954");
    LargeInteger b = new LargeInteger("123456789");
    LargeInteger c = a.plus(b);
    System.out.println( c.toString() );
    System.out.println( a.toString() );
    System.out.println( b.toString() );
    /** Calculates the sum of this LargeInteger object with the one passed
    * as a parameter.
    * @param other The number to add to the current value.
    * @return The sum of this LargeInteger and the value passed as a
    * parameter.
    public LargeInteger plus(LargeInteger other) {
         int i = 0;
    LargeInteger result = new LargeInteger("0");
    int carry = 0;
    ListIterator onfiltered = digits.listIterator();
    ListIterator two = other.digits.listIterator();
    //Add digits in linked list
    for (; i < digits.size() && i < other.digits.size(); i++) {
    result.digits.addFirst(
    new Integer(
    (((Integer) digits.get(i)).intValue()
    + ((Integer) other.digits.get(i)).intValue()
    + carry)
    % 10));
    carry =
    (((Integer) digits.get(i)).intValue()
    + ((Integer) other.digits.get(i)).intValue()
    + carry)
    / 10;
    onfiltered.next();
    two.next();
    //Append any remaining digits from this value to the result's
    //left
    for(; i < digits.size();i++){
         result.digits.addFirst(new Integer((((Integer)digits.get(i)).intValue() + carry) % 10));
         carry = (((Integer)digits.get(i)).intValue() + carry) / 10;
         onfiltered.next();
    //Append any remaining digits from the other value to the result's
    //left
    for(; i < digits.size();i++){
         result.digits.addFirst(new Integer((((Integer)other.digits.get(i)).intValue() + carry) % 10));
         carry = (((Integer)other.digits.get(i)).intValue() + carry) / 10;
         two.next();
    if(carry != 0){
         result.digits.addFirst(new Integer(carry));
    return result;
    } // end plus

    Use a debugger.
    Or put in some debugging statements.

  • Linked List

    Hello
    I got a problem trying to store arrays in a linked list. i need to store 3 numbers in the array(eg a[0], a[1], a[2]) in a link list and another 3 in another and so on. (dnt have to use arrays but i used it to store the 3 number in one linked list)
    when i use arrays to store em it says cants store int cos my links list stores objects! i cant convert the numbers to object cos then i need to search for the particular set of numbers from the link list.
    if some one could help me by explaing wat i could do i will be gratefull
    thanks!!!

    Yes, as danperkins suggests you can insert groups of three int[] into your list ...and then as your search through the list, pull each group of three ints back out of each list node and analyze them on the spot to see if they are equal.
    What I was suggesting is to encapsulate your three ints into a class that becomes an entity called, say ...ThreeInts. Then, you could add the functionality inside this object to determine if it was equal to another object of the same type. Same thing as danperkins suggestion, except one requires external routines to process each node and the other (mine) uses an object that knows how to process itself.
    This is a fundamental facet of OOP programming ...representing data in objects that know how to store their values ...know how to express themselves ...know how to order and compare themselves ...etc, etc, etc.
    The way I see it, I have given you the structures required to complete your task ...you just have to operate on them and incorporate them into your code. If you don't see how to do this, then I don't really know what else to suggest ...sorry.
    semi - psuedocode created from what you have so far might be as follows.
    // Insert ThreeInts objects into linked list...
    // Where array is original array of 120 ints...
    for (int k=0, k<array.length; k++) {
      if( (k%3)==0 && k!=0 ) {
        list.add(new ThreeInts(array[k-2],array[k-1],array[k]);
    // Search for specific ThreeInts objects in linked list...
    // i.e. "find an object in the list equal to the object ThreeInts(3,5,8)"
    ThreeInts found = searchList( new ThreeInts(3,5,8) );Basically, the ThreeInts object is a class that knows how to hold three integers ...knows how to give these three integers back to you ...and most importantly knows how to compare itself to another ThreeInts object and say "yes, I am the same" ...or "No, I am not the same". That is what MyCuteLittleClass will do ...you just have to change its name to ThreeInts. Beyond this, I don't know what else to say.

  • Link Lists Problem!!!

    I have array of employees that i am inserting into Linked List. Everything is working fine except my forward and backward displays are swapped.
    Forward should display Emp in ascending order and Backward should display the other way around. Mine are swapped? What am i missing?
        public void insertFirst(Emp e)
            Link newLink = new Link(st);
            if(isEmpty())
                last = newLink;
            else
                first.previous = newLink;
            newLink.next = first;
            first = newLink;
        public void displayForward()
            System.out.print("\n\n");
            System.out.print("Doubly-Linked List of Employees Using Forward Pointers\n\n");
            Link current = first;
            while(current != null)
                current.displayLink();
                current = current.next;
            System.out.println(" ");
        public void displayBackward()
            System.out.print("Doubly-Linked List of Employees Using Backward Pointers\n\n");
            Link current = last;
            while(current != null)
                current.displayLink();
                current = current.previous;
            System.out.println(" ");
            }

    What are you using to add items to the list? Not this insertFirst method that inserts at the beginning, right? You are instead using a different method that inserts at the end of the list, correct?

Maybe you are looking for