Linked lists - changing nodes

Hello,
I have a double linked list where I want to change one node to another and change its references at the same time.
The nodes are not together i.e. they do not appear in the list consectutively.
I need to swap like B and D - I have managed to do swaps like A and B, and C and D (that took a while).
Is this logic correct (I am using temporary nodes):
if(f1 != (f2 - 1))
     Object temp = object1;
     Object temp2 = object2;
     object1.getPrevious().setNext(object2);
     object2.getNext().setPrevious(object1);
     object1.getNext().setPrevious(object2);
     object2.getPrevious().setNext(object1);
     object1.setPrevious(temp2.getPrevious());
     object1.setNext(temp2.getNext());
     object2.setPrevious(temp.getPrevious());
     object2.setNext(temp.getNext());
If this logic is not correct then please only give hints as to why.
Cheers

Hello,
I have a double linked list where I want to change
one node to another and change its references at the
same time.
The nodes are not together i.e. they do not appear in
the list consectutively.
I need to swap like B and D - I have managed to do
swaps like A and B, and C and D (that took a while).
Is this logic correct (I am using temporary nodes):
if(f1 != (f2 - 1))
     Object temp = object1;
     Object temp2 = object2;
     object1.getPrevious().setNext(object2);
     object2.getNext().setPrevious(object1);
     object1.getNext().setPrevious(object2);
     object2.getPrevious().setNext(object1);
     object1.setPrevious(temp2.getPrevious());
     object1.setNext(temp2.getNext());
     object2.setPrevious(temp.getPrevious());
     object2.setNext(temp.getNext());
If this logic is not correct then please only give
hints as to why.
CheersI didn't check your logic, but I think that there are errors in it since I saw these lines:
object1.setPrevious(temp2.getPrevious());
object1.setNext(temp2.getNext());
object2.setPrevious(temp.getPrevious());
object2.setNext(temp.getNext()); temp and temp2 are not copies of object1 and object2. They are references to the same object, so when you do e.g. object1.getPrevious().setNext() you also change previous->next for temp.
temp == object1
temp2 == object2
Kaj

Similar Messages

  • Linked List  - deleeting nodes - HELP!

    How do I delete all occurences of the nodes with the same parameters in the linked list ?
    example:
    Node1-> Node2 ->Node3->Node4->Node5
    Node1, Node4, and Node5 have the same String value, how do I delete them in one method without breaking the linked list ?
    thanks

    Hi,
    You have iterate thru the linked list remove one by one. Also have look at other collection classes like HashSet or HashMap for fast retrieval.

  • Help with Stacked linked lists with nodes.

    I have 5 elements, { object1, object2, object3, object4, object5}; and I add then to the stack from object1 to object5 (from left to right). So the head node > object 5 > object 4 > object3> object2 > object1. (> represents points to.) So i made a method to get the nth element of the list in the order I input it to the list. The method is called ElementsAt(int i). But some reason, it always returns the last object in the list. I included my entire code because there may be something wrong somewhere else that maybe causing it.
    Note: There is also a list interface.
    public class MyList implements List {
         * The head node.
         private Node head;
         * The node it is currently reading
         private Node curr;
         * The previous node it has read.
         private Node prev;
         * A blank Node
         private Node blank;
         * The number of elements in the list
         private int numItems;
         * Default constructor
         public MyList() {
              numItems = 0;
              head = null;
         * Add an element in front of the list.
         * @param o The object to be added.
         public void addFront(Object o){
              if(head == null) {
                   head = new Node (o, null);
              else{
                   blank = new Node(o,null);
                   curr = head;
                   while (curr != null){
                        prev = curr;
                        curr = curr.getNext();
                   blank.setNext(curr);
                   prev.setNext(blank);
              numItems +=1;
         * Add an element in the back of the list.
         * @param o The object to be added.
         public void addBack(Object o){
              curr = head;
              if (head == null){
                   head = new Node(o ,null);
              else {
                   head = new Node(o, curr);
              numItems +=1;
         * Determine whether the list contains a certain object.
         * @param o The object it searches through the list to
         * see if it is present.
         * @ returns a boolean that describes whether object is
         * in the list.
         public boolean contains(Object o){
              boolean present = false;
              curr = head;
              while ((curr != null) && (present != true)){
                   present = (o.equals(curr.getElement()));
                   curr.setNext(curr.getNext());
              return present;
         /** Remove an object in the list if it is in the list.
         * @param o The object it wants to remove.
         public void remove(Object o){
              if(head ==null){
                   return ;
              if(head.getElement().equals(o)){
                   head = head.getNext();
                   numItems -=1;
              else{
                   prev = head;
                   curr = head.getNext();
                   while ((curr!=null) && (curr.getElement() !=o)){
                        prev = curr;
                        curr = curr.getNext();
                   if (curr!=null){
                        blank = curr.getNext();
                        prev.setNext(blank);
                        numItems-=1;
         /** Determine what object is at the nth place of the list.
         * @param i the nth place of the list
         * if the number is higher than the list, it is invalid.
         * @returns The element of the nth position of the list.
         public Object elementAt(int i){
              curr = head;
              Object blank = "";
              if ( i > numItems){
                   return null;
              else{
                   i = numItems - i;
                   for (int j=1; j<=i; j++){
                        if(curr!=null){
                             blank = curr.getElement();
                             curr = curr.getNext();
                   return blank;
         /** Determine the size of the list.
         * @returns The size of the list
         public int size() {
              return numItems ;
         /** Makes the list empty
         public void makeEmpty() {
              head = new Node(null,null);
              numItems = 0;
         /** Returns The list as a string.
         * @returns String containing all elemnts of the list.
         public String toString(){
              String sum = "";
              curr = head.getNext();
              blank = head;
              prev = head;
              if(curr==null){
                   prev.setNext(null);
                   curr=prev;
              while(curr != null)
                   if(curr.getNext() ==null){
                        sum += "\n" + curr.getElement();
                        curr.setNext(null);
                   if(curr.getNext()==null)
                        prev.setNext(null);
                        prev = blank;
                        curr = prev.getNext();
                   else{
                        curr = curr.getNext();
                        prev= prev.getNext();
              if (head.getElement() !=null)
              sum +="\n" + head.getElement();
              return sum;
    }this is the program i use to test it.
    public class MyListTester {
         public static void main (String [] args)
              List list = new MyList();
              String one = "Object One";
              String two = "Object Two";
              String three = "Object Three";
              int five = 5;
              list.addFront(one);
              list.addFront(two);
              list.addFront(three);
              list.addFront(five);
              System.out.println(list);
              System.out.println();
              System.out.println(list.size());
              System.out.println(list.elementAt(2));
                    //this should print out object Two, but doesn't
              System.out.println(list.elementAt(3));
                    //this should print out object Three, but doesn't
    }

    chuang7 wrote:
    So i made a method to get the nth element of the list in the order I input it to the list.
    * The node it is currently reading
    private Node curr;
    * The previous node it has read.
    These ('curr' and 'prev') should be local variables in the methods that need them, not instance variables.
    public void addFront(Object o)
    while (curr != null){
         prev = curr;
         curr = curr.getNext();
    blank.setNext(curr);At this point 'curr' is always null so this line is redundant.
    public void addBack(Object o)You can reduce this method to two lines of code.
    public boolean contains(Object o)
    curr.setNext(curr.getNext());You are modifying the list inside the contains method?
                   for (int j=1; j<=i; j++){Rethink this loop.
    public String toString()
         prev.setNext(null);
    if(curr.getNext() ==null)
         sum += "\n" + curr.getElement()+"->"+curr.getNext();
         curr.setNext(null);
    if(curr.getNext()==null)
         prev.setNext(null);
         prev = blank;
         curr = prev.getNext();You are modifying the list in the toString() method?

  • Putting a class of objects in a Linked List?

    Hi,
    I copied a program from a book and I want to edit it and put studentRecord class in the Linked List. I've tried to play about with datum, but everything I try doesn't work. Can someone help me out? How could I put studentRecord in the LinkedList?
    import java.io.*;
    class IO
         static BufferedReader keyboard = new
              BufferedReader(new InputStreamReader(System.in));
         static PrintWriter screen = new PrintWriter(System.out, true);
    class studentRecord
         private String name;
         private int IDNumber;
    class LinkedList
         class Node
              protected Object datum;
              protected Node link;
              public Node() {}
              public Node(Object item, Node pointer)
                   datum = item;
                   link = pointer;
         private Node head;
         private Node tail;
         private Node temporary;
         private int nodeCount = 0;
         //constructor
         public LinkedList()
              head = null;
              tail = null;
              temporary = null;
         //method to insert an object into the linked list
         public void insert(Object datum)
              if (head == null) // list empty
                   head = new Node(datum, head);
                   tail = head;
              else
                   temporary = new Node(datum, temporary);
                   tail.link = temporary;
                   tail = temporary;
                   temporary = null;
              nodeCount++;
    Full program can be found: http://dil3mma.tripod.com/LinkedList.txt
    Thanks in advance.

    Hi jverd,
    Thanks for replying. I've tried to change the program liked you said but there is 1 error I can't seem to fix(Im sure there are more tho). The error is "cannot resolve symbol" I typed in caps the line it happens on so it's easy to see. Any idea what it could be? Is it cause I'm comparing a String with Object?
    import java.io.*;
    class IO
         static BufferedReader keyboard = new
              BufferedReader(new InputStreamReader(System.in));
         static PrintWriter screen = new PrintWriter(System.out, true);
    class sRecord
         private String name;
         private int IDNumber;
    class LinkedList
         class Node
              protected sRecord datum;
              protected Node link;
              public Node() {}
              public Node(sRecord item, Node pointer)
                   datum = item;
                   link = pointer;
         private Node head;
         private Node tail;
         private Node temporary;
         private int nodeCount = 0;
         //constructor
         public LinkedList()
              head = null;
              tail = null;
              temporary = null;
         //method to insert an object into the linked list
         public void insert(sRecord datum)
              if (head == null) // list empty
                   head = new Node(datum, head);
                   tail = head;
              else
                   temporary = new Node(datum, temporary);
                   tail.link = temporary;
                   tail = temporary;
                   temporary = null;
              nodeCount++;
         //method to delete an object from the linked list
         public boolean delete(Object scrap)
              Node previous = head;
              //for every node in the linked list
              for (Node current = head; current != null; current = current.link)
                   //node to be deleted is at the head of the list
                   if (current.datum.equals(scrap) && previous == current)
                        head = current.link;
                        if (head == null) tail = null;
                        nodeCount--;
                        return true;
                   //node to be deleted is after the first node and before the last
                   else if (current.datum.equals(scrap) && (current.link != null))
                        previous.link = current.link;
                        nodeCount--;
                        return true;
                   //node to be deleted is at the ned of list
                   else if (current.datum.equals(scrap) && (current.link == null))
                        tail = previous;
                        previous.link = null;
                        nodeCount--;
                        return true;
                   previous = current;
              return false;
         //method to display the contents of a linked list
         public void displayList()
              Node temporary = head;
              if (head == null)
                   IO.screen.println("linked list is empty");
                   return;
              while (temporary != null)
                   IO.screen.println(temporary.datum);
                   temporary = temporary.link;
         //method to return true if the linked list is empty
         public boolean isEmpty()
              return (nodeCount == 0);
         //method to return the number of nodes in the linked list
         public int nodes()
              return nodeCount;
         //method to display a menu to insert data into the linked list
         static private char menu()
              char response = '\u0000';
              IO.screen.println("Do you want to ");
              IO.screen.print("nsert, [D]elete, [L]ist, [E]xit? ");
              IO.screen.flush();
              boolean done=false;
              do
                   try
                        String data = IO.keyboard.readLine();
                        response = Character.toUpperCase(data.charAt(0));
                        done = true;
                   catch (Exception e)
                        IO.screen.println("Please input a single character I, D, L or E");
              } while (! done);
              return response;
         static public void main(String[] args) throws IOException
              LinkedList list = new LinkedList();
              String datum;
              char choice;
              //get information from menu
              choice = menu();
              for (;;)
                   //Menu
                   switch (choice)
                        case 'I' :
                             IO.screen.println("type quit to finish input");
                             IO.screen.print("Enter a word ");
                             IO.screen.flush();
                             datum = IO.keyboard.readLine();
                             while (! datum.equals("quit"))
    THE ERROR HAPPENS HERE ON THIS LINE          list.insert(datum.name);
                                  IO.screen.print("Enter another word");
                                  IO.screen.flush();
                                  datum = IO.keyboard.readLine();
                             break;
                   case 'D' :
                        //if list is empty deletion not possible
                        if (list.isEmpty())
                             IO.screen.println("linked list is empty");
                             break;
                        IO.screen.println("type quit to finish input");
                        IO.screen.print("Delete? ");
                        IO.screen.flush();
                        datum = IO.keyboard.readLine();
                        while (! datum.equals("quit"))
                             if (list.delete(datum))
                                  IO.screen.println(datum+" was scrapped!");
                             //if list is empty deletion is not possible
                             if (list.isEmpty())
                                  IO.screen.println("linked list is empty");
                                  break;
                             IO.screen.print("Delete? ");
                             IO.screen.flush();
                             datum = IO.keyboard.readLine();
                        break;
                   case 'L' :
                        list.displayList();
                        IO.screen.println("number of nodes " + list.nodes());
                        break;
                   case 'E' : System.exit(0);
              //get information from menu
              choice = menu();

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

  • Linked List bubbleSort problems

    I'm trying to implement a bubbleSort (with a insertionSort and selectionSort) on a linked list, but can't seem to get it working. Any tips on correcting the bubbleSort, and maybe some for the other two? Thanks!!!
    public class sortingMethods {
    public sortingMethods() {}
    public void bubbleSort(LinkedList list) {
    if(list.isEmpty())
    System.out.println("List is currently empty.");
    else if (list.size() == 1)
    System.out.println("List is already sorted.");
    else {
    Node current = list.getHead();
    Node next = current.getNext();
    Node temp;
    int counter = 0;
    boolean exchangeMade = true;
    while(counter < (list.size() - 1) && exchangeMade) {
    counter++;
    exchangeMade = false;
    for(int i = 1; i <= (list.size() - counter); i++) {
    if(current.getData() > next.getData()) {
    temp = current;
    current = next;
    next = temp;
    exchangeMade = true;
    public void selectionSort(LinkedList list) {
    if(list.isEmpty())
    System.out.println("List is currently empty.");
    else if (list.size() == 1)
    System.out.println("List is already sorted.");
    else{}
    public void insertionSort(LinkedList list){
    if(list.isEmpty())
    System.out.println("List is currently empty.");
    else if (list.size() == 1)
    System.out.println("List is already sorted.");
    else {
    public class LinkedList {
    private Node head;
    private int count;
    public LinkedList() {
    head = null;
    count = 0;
    public LinkedList(LinkedList rhs) {   //Copy constructor
    head = rhs.head;
    count = rhs.count;
    public void orderedInsert(int item) {   //Inserts the Node in the right position - Ascending
    Node back = null;
    Node newNode = new Node(item);
    Node pointer = head;
    boolean found = false;
    while(pointer != null && !found) {
    if(pointer.getData() > item)
    found = true;
    else {
    back = pointer;
    pointer = pointer.getNext();
    newNode.setNext(pointer);
    if(back == null) {
    head = newNode;
    count++;
    else {
    back.setNext(newNode);
    count++;
    public void insert(int item) {   //Inserts at front of list
    Node newnode = new Node(item);
    if(head == null)
    head = newnode;
    else {
    newnode.setNext(head);
    head = newnode;
    public void orderedRemove(int item) {   //Searches and removes selected Node
    Node back = null;
    boolean found = false;
    Node pointer = head;
    while(pointer != null && !found) {
    if(pointer.getData() == item)
    found = true;
    else {
    back = pointer;
    pointer = pointer.getNext();
    if(found)
    if(back == null) {
    head = pointer.getNext();
    count--;
    } else {
    back.setNext(pointer.getNext());
    count--;
    } else
    System.out.println("Data not found in list.");
    public void remove() {   //Removes from front of list
    if(head == null)
    System.out.println("List is currently empty.");
    else {
    Node n = head;
    head = head.getNext();
    n.setNext(null);
    count--;
    public boolean isEmpty() {
    if(head == null)
    return true;
    else
    return false;
    public void print() {
    Node current = head;
    while(current != null) {
    System.out.println(current.getData());
    current = current.getNext();
    public int size() {return count;}
    public Node getHead() {return head;}
    } //End LinkedList class

    I'm still having problems! Now the code just seems to go through an endless loop.
        public void bubbleSort(LinkedList list) {
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                boolean exchangeMade = true;           
                int counter = 0;
                Node current = list.getHead();
                Node next = current.getNext();
                Node temp;
                while(counter < (list.size() - 1) && exchangeMade) {
                    counter++;
                    exchangeMade = false;
                    for(int i = 1; i <= (list.size() - counter); i++) {
                        if(current.getData() > next.getData()) {
                            temp = current;
                            current.setNext(next);
                            next.setNext(temp);
                            exchangeMade = true;
        }And here is the rest of my code...
    package cs321_assignment1;
    public class LinkedList {   //Doubly Linked List
        private Node head;
        private int count;
        public LinkedList() {
            head = null;
            count = 0;
        public LinkedList(LinkedList rhs) {   //Copy constructor
            head = rhs.head;
            count = rhs.count;
        public void orderedInsert(int item) {   //Inserts the Node in the right position - Ascending
            Node back = null;
            Node newNode = new Node(item);
            Node pointer = head;
            boolean found = false;
            while(pointer != null && !found) {
                if(pointer.getData() > item)
                    found = true;
                else {
                    back = pointer;
                    pointer = pointer.getNext();
            newNode.setNext(pointer);
            if(back == null) {
                head = newNode;
                count++;
            else {
                back.setNext(newNode);
                count++;
        public void insert(int item) {   //Inserts at front of list
            Node newnode = new Node(item);
            if(head == null)
                head = newnode;
            else {
                newnode.setNext(head);
                head = newnode;
            count++;
        public void orderedRemove(int item) {   //Searches and removes selected Node
            Node back = null;
            boolean found = false;
            Node pointer = head;
            while(pointer != null && !found) {
                if(pointer.getData() == item)
                    found = true;
                else {
                    back = pointer;
                    pointer = pointer.getNext();
            if(found)
                if(back == null) {
                head = pointer.getNext();
                count--;
                } else {
                back.setNext(pointer.getNext());
                count--;
                } else
                    System.out.println("Data not found in list.");
        public void remove() {   //Removes from front of list
            if(head == null)
                System.out.println("List is currently empty.");
            else {
                Node n = head;
                head = head.getNext();
                n.setNext(null);
                count--;
        public boolean isEmpty() {
            if(count == 0)
                return true;
            else
                return false;
        public void print() {
            Node current = head;
            while(current != null) {
                System.out.println(current.getData());
                current = current.getNext();
        public int size() {return count;}
        public Node getHead() {return head;}
        public void setHead(Node n) {head = n;}
    } //End LinkedList class
    package cs321_assignment1;
    public class Node {
        private int data;
        private Node next;
        public Node() {next = null;}
        public Node(int d) {
            next = null;
            data = d;
        public int getData() {return data;}
        public void setData(int newData) {data = newData;}
        public Node getNext() {return next;}
        public void setNext(Node newNode) {next = newNode;}
    }I can't figure this out, and I really need some help. Hopefully after I solve this, the selection and insertion sorts will be a little simpler. Any help will really be appreciated.

  • Is my code a Linked Lists or not?

    Hello everyone,
    [I hope I am in the right forum]
    I am trying to learn how to implement Linked Lists with Java. I have written a small code and I would appreceate it a lot if any one would be kind enough to check if this code is really a linked list.
    I tried to make a list with 3 nodes, with no helping methods for adding and removing nodes. Just a simple example. This is my code:
    public class myList{
         public static final long serialVersionUID = 24362462L;
         //node pointer important to define private, so not share same value
         private myList pointer;
         //node data
         private String nodeData;
    public static void main(String args[]){
    //Give memory to nodes
    myList Node1 = new myList();
    myList Node2 = new myList();
    myList Node3 = new myList();
    //Make Node1
    Node1.pointer = Node2;//give value to pointer
    Node1.nodeData = "Hi i am data contained in Node 1.";
    //Make Node2
    Node2.pointer = Node3;
    Node2.nodeData = "Hi i am data contained in Node 2.";
    //Make Node3
    Node3.pointer = null;
    Node3.nodeData = "Hi i am data contained in Node 3.";
    //Display Data
    System.out.println(Node1.nodeData);
    System.out.println(Node2.nodeData);
    System.out.println(Node3.nodeData);
    //Display pointers
    System.out.println("Hi this is Node2 ==============>:"+Node2);
    System.out.println("This is the value of pointer of Node1:"+Node1.pointer);
    System.out.println("Hi this is Node3===============>:"+Node3);
    System.out.println("This is the value of pointer of Node2:"+Node2.pointer);
    }//main
    }//class
    /***** OUTPUT ***** OUTPUT ***** OUTPUT ***** OUTPUT *****
    Hi i am data contained in Node 1.
    Hi i am data contained in Node 2.
    Hi i am data contained in Node 3.
    Hi this is Node2 ========================>:myList@16f0472
    This is the value of pointer of Node 1 ==>:myList@16f0472
    Hi this is Node3 ========================>:myList@18d107f
    This is the value of pointer of Node 2 ==>:myList@18d107f
    Press any key to continue...
    Thank you very much,
    JMelsi

    Happy to advise. Here we go. :)
    Firstly, you'll want to post your code in code tags. They make your code more legible, thus making it easier and therefore more likely that someone responds. ;)
    Second, it would be more appropriate for class names (such as "myList") to start with an upper-case letter (such as "MyList"). Additionally, the class in question does not represent a whole list but instead a node, so you might want to call it "MyListNode" or something similar.
    Strictly speaking, your code is definitely that of a linked list of nodes. For example, one could print all of the contents in your list with code like this:
    myList node = ...; // assign to the first node
    while (node!=null) // as long as there is a node
        System.out.println(node.nodeData); // print the data in this node
        node = node.pointer; // move on to the next node
    }Note that, in the above code, I didn't have to know how many nodes were in your list or have any references to them beforehand. :) That's the power in the data structure you're creating.
    Enjoy!

  • Linked List: print contents

    How can I print out the contents of a linked list whose nodes are made up of Data Objects?
    If I do, "System.out.println("Node: " + detailsList);"
    I get this kinda stuff:
    [my.package.Switch@df6ccd, my.package.Pbx@601bb1, my.package.Switch@1ba34f2]
    thanks

    Override the toString() method in your data object.
    Example:
    public String toString() {
        return name + " | " + ip + " | " + mac;
    }

  • Changing data in a linked list object.

    hi,
    i'm still pretty new to java, so bear with me if i am making stupid mistakes, heh.
    i'm having trouble with changing data in an object stored in a singly-linked list. i've created a class that will store polynomials in sorted order (descending) in a singly-linked list. each linked list is one polynomial, and each node references to a polynomial object that stores two ints: the coefficient and the exponent of that term.
    i'm having trouble when it comes to 'collecting like terms,' though. here's a rough skeleton of my code:
    public class Polynomial
    private LinkedList polynoList;
    private LinkedListItr Itr;
    private int coeff;
    private int exponent;
    public Polynomial()
    zeroPolynomial();
    } // this constructor sets up an empty linked list
    public Polynomial( int c, int e )
    coeff = c;
    exponent = e;
    } // this creates a Polynomial object storing the two ints
    public void zeroPolynomial()
    polynoList = new LinkedList();
    theItr = polynoList.zeroth();
    } // this method creates the empty linked list and sets the
    //iterator on the zeroth node.
    //various other methods are here, not relevant to my post
    //this next method is the one i am having trouble with.
    //it takes two ints as parameters, the coefficient
    //and the exponent.
    public void insertTerm( int c, int e )
    //...i have a few if/then statements here
    //so that the terms can be inserted in descending order.
    LinkedListItr tester = polynoList.first();
    //the 'tester' iterator is set on the first node
    //this following if statement retrieves the exponent
    //in the current node by casting the information
    //retrieved from the LinkedList retrieve() method
    //into Polynomial, then compares it to the current
    //exponent. if they are equal, i want to add the
    //coefficients.
    if( e == ((Polynomial)tester.retrieve()).getExp() )
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    //a main method goes here wherein the user can insert
    //terms, print the polynomial, etc.
    }//end Polynomial class
    can anyone help me out? the code i'm using compiles correctly, but it does not change the value of the current coeff variable as i'd like to think it should. any input would be GREATLY appreciated, thanks!

    hey,
    thanks for the reply...
    i am sure that ((Polynomial)tester.retrieve()).getExp() will return an int equal to 'e.' i tried this:
    System.out.println("e="+e);
    System.out.println((Polynomial)tester.retrieve()).getExp());
    if( e == ((Polynomial)tester.retrieve()).getExp() ){
    this.coeff = ((Polynomial)tester.retrieve()).getCoeff() + c;
    System.out.println( "this.coeff = " + this.coeff );
    with that, the output showed that e and the getExp() output were the same. it also showed (as output) that this.coeff did change in value, but when i tried this:
    System.out.println( ((Polynomial)tester.retrieve()).getCoeff() )
    to check if the value changed within the object, it didn't. this.coeff changed, but the actual coeff variable in the object didn't.
    any ideas?

  • Splitting a Linked List at a Given Node, into Two Sublists??

    My code just will not work!! Any help would be appreciated! My problem is in the last method SplitAt. These are the conditions set and my code:
    Splitting a Linked List at a Given Node, into Two Sublists
    a. Add the following as an abstract method to the class
    LinkedListClass:
    public void splitAt (LinkedListClass<T> secondList, T item);
    //This method splits the list at the node with the info item into two sublists.
    //Precondition: The list must exist.
    //Postcondition: first and last point to the first and last nodes of the first sublist,
    // respectively. secondList.first and secondList.last point to the first
    // and last nodes of the second sublist.
    Consider the following statements:
    UnorderedLinkedList<Integer> myList;
    UnorderedLinkedList<Integer> otherList;
    Suppose myList points to the list with the elements 34, 65, 18, 39, 27, 89, and 12 (in this order). The statement
    myList.splitAt(otherList, 18);
    splits myList into two sublists: myList points to the list with elements 34 and 65, and otherList points to the sublist with elements 18, 39, 27, 89, and 12.
    b. Provide the definition of the method splitAt in the class UnorderedLinkedList. Also write a program to test your method.
    public class UnorderedLinkedList<T> extends LinkedListClass<T>
    //Default constructor
    public UnorderedLinkedList()
    super();
    //Method to determine whether searchItem is in
    //the list.
    //Postcondition: Returns true if searchItem is found
    // in the list; false otherwise.
    public boolean search(T searchItem)
    LinkedListNode<T> current; //variable to traverse
    //the list
    boolean found;
    current = first; //set current to point to the first
    //node in the list
    found = false; //set found to false
    while (current != null && !found) //search the list
    if (current.info.equals(searchItem)) //item is found
    found = true;
    else
    current = current.link; //make current point to
    //the next node
    return found;
    //Method to insert newItem in the list.
    //Postcondition: first points to the new list
    // and newItem is inserted at the
    // beginning of the list. Also,
    // last points to the last node and
    // count is incremented by 1.
    public void insertFirst(T newItem)
    LinkedListNode<T> newNode; //variable to create the
    //new node
    newNode =
    new LinkedListNode<T>(newItem, first); //create and
    //insert newNode before
    //first
    first = newNode; //make first point to the
    //actual first node
    if (last == null) //if the list was empty, newNode is
    //also the last node in the list
    last = newNode;
    count++; //increment count
    //Method to insert newItem at the end of the list.
    //Postcondition: first points to the new list and
    // newItem is inserted at the end
    // of the list. Also, last points to
    // the last node and
    // count is incremented by 1.
    public void insertLast(T newItem)
    LinkedListNode newNode; //variable to create the
    //new node
    newNode =
    new LinkedListNode(newItem, null); //create newNode
    if (first == null) //if the list is empty, newNode is
    //both the first and last node
    first = newNode;
    last = newNode;
    else //if the list is not empty, insert
    //newNode after last
    last.link = newNode; //insert newNode after last
    last = newNode; //set last to point to the
    //actual last node
    count++;
    }//end insertLast
    //Method to delete deleteItem from the list.
    //Postcondition: If found, the node containing
    // deleteItem is deleted from the
    // list. Also, first points to the first
    // node, last points to the last
    // node of the updated list, and count
    // is decremented by 1.
    public void deleteNode(T deleteItem)
    LinkedListNode<T> current; //variable to traverse
    //the list
    LinkedListNode<T> trailCurrent; //variable just
    //before current
    boolean found;
    if ( first == null) //Case 1; the list is empty
    System.err.println("Cannot delete from an empty "
    + "list.");
    else
    if (first.info.equals(deleteItem)) //Case 2
    first = first.link;
         if (first == null) //the list had only one node
         last = null;
         count--;
    else //search the list for the given info
    found = false;
    trailCurrent = first; //set trailCurrent to
    //point to the first node
    current = first.link; //set current to point to
    //the second node
    while (current != null && !found)
    if (current.info.equals(deleteItem))
    found = true;
    else
    trailCurrent = current;
    current = current.link;
    }//end while
    if (found) //Case 3; if found, delete the node
    count--;
    trailCurrent.link = current.link;
    if (last == current) //node to be deleted
    //was the last node
    last = trailCurrent; //update the value
    //of last
    else
    System.out.println("Item to be deleted is "
    + "not in the list.");
    }//end else
    }//end else
    }//end deleteNode
    public void splitAt(LinkedListClass<T> secondList, T item)
    LinkedListNode<T> current;
    LinkedListNode<T> trailCurrent;
    int i;
    boolean found;
    if (first==null)
    System.out.println("Empty.");
    first=null;
    last=null;
    count--;
    else
         current=first;
         found=false;
         i=1;
         while(current !=null &&!found)
              if(current.info.equals(secondList))
                   found= true;
                   else
                        trailCurrent=current;
                        i++;
         if(found)
              if(first==current)
                   first=first;
                   last=last;
                   count=count;
                   count=0;
              else
                   first=current;
                   last=last;
                   last=null;
                   count = count- i+1;
                   count = i-1;
              else
                   System.out.println("Item to be split at is "
    + "not in the list.");
              first=null;
              last=null;
              count=0;
    }

    I dont have a test program at all. The program is supposed to prompt for user input of numbers. (it does) Take the input and end at input of -999 (it does). Then it asks user where it wants to split list (it does). When I enter a number it does nothing after that. I am going to post updated code and see if that helps along with all the classes. Thanks!
    This is the class to prompt:
    import java.util.*;
    public class Ch16_ProgEx6
        static Scanner console = new Scanner(System.in);
         public static void main(String[] args)
             UnorderedLinkedList<Integer> list
                              = new UnorderedLinkedList<Integer>();
            UnorderedLinkedList<Integer> subList =
                              new UnorderedLinkedList<Integer>();
             Integer num;
             System.out.println("Enter integers ending with -999.");
             num = console.nextInt();
             while (num != -999)
                 list.insertLast(num);
                 num = console.nextInt();
            System.out.println();
            System.out.println("list: ");
            list.print();
            System.out.println();
            System.out.println("Length of list: " + list.length());
            System.out.print("Enter the number at which to split list: ");
            num = console.nextInt();
            list.splitAt(subList, num);
            System.out.println("Lists after splitting list");
            System.out.print("list: ");
            list.print();
            System.out.println();
            System.out.println("Length of list: " + list.length());
            System.out.print("sublist: ");
            subList.print();
            System.out.println();
            System.out.println("Length of sublist: " + subList.length());
    }This is the ADT:
    public interface LinkedListADT<T> extends Cloneable
        public Object clone();
           //Returns a copy of objects data in store.
           //This method clones only the references stored in
           //each node of the list. The objects that the
           //list nodes point to are not cloned.
        public boolean isEmptyList();
           //Method to determine whether the list is empty.
           //Postcondition: Returns true if the list is empty;
           //               false otherwise.
        public void initializeList();
           //Method to initialize the list to an empty state.
           //Postcondition: The list is initialized to an empty
           //               state.
        public void print();
           //Method to output the data contained in each node.
        public int length();
           //Method to return the number of nodes in the list.
           //Postcondition: The number of nodes in the list is
           //               returned.
        public T front();
           //Method to return a reference of the object containing
           //the data of the first node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the first node
           //               is returned.
        public T back();
           //Method to return a reference of object containing
           //the data of the last node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the last node
           //               is returned.
        public boolean search(T searchItem);
           //Method to determine whether searchItem is in the list.
           //Postcondition: Returns true if searchItem is found
           //               in the list; false otherwise.
        public void insertFirst(T newItem);
           //Method to insert newItem in the list.
           //Postcondition: newItem is inserted at the
           //               beginning of the list.
        public void insertLast(T newItem);
           //Method to insert newItem at the end of the list.
           //Postcondition: newItem is inserted at the end
           //               of the list.
        public void deleteNode(T deleteItem);
           //Method to delete deleteItem from the list.
           //Postcondition: If found, the node containing
           //               deleteItem is deleted from the
           //               list.
        public void splitAt(LinkedListClass<T> secondList, T item);
    }This is the linked list class:
    import java.util.NoSuchElementException;
    public abstract class LinkedListClass<T> implements LinkedListADT<T>
        protected class LinkedListNode<T> implements Cloneable
            public T info;
            public LinkedListNode<T> link;
               //Default constructor
               //Postcondition: info = null; link = null;
            public LinkedListNode()
                info = null;
                link = null;
               //Constructor with parameters
               //This method sets info pointing to the object to
               //which elem points to and link is set to point to
               //the object to which ptr points to.
               //Postcondition:  info = elem; link = ptr;
            public LinkedListNode(T elem, LinkedListNode<T> ptr)
                info = elem;
                link = ptr;
               //Returns a copy of objects data in store.
               //This method clones only the references stored in
               //the node. The objects that the nodes point to
               //are not cloned.
            public Object clone()
                LinkedListNode<T> copy = null;
                try
                    copy = (LinkedListNode<T>) super.clone();
                catch (CloneNotSupportedException e)
                    return null;
                return copy;
               //Method to return the info as a string.
               //Postcondition: info as a String object is
               //               returned.
            public String toString()
                return info.toString();
        } //end class LinkedListNode
        public class LinkedListIterator<T>
            protected LinkedListNode<T> current;  //variable to
                                                  //point to the
                                                  //current node in
                                                  //list
            protected LinkedListNode<T> previous; //variable to
                                                  //point to the
                                                  //node before the
                                                  //current node
               //Default constructor
               //Sets current to point to the first node in the
               //list and sets previous to null.
               //Postcondition: current = first; previous = null;
            public LinkedListIterator()
                current = (LinkedListNode<T>) first;
                previous = null;
               //Method to reset the iterator to the first node
               //in the list.
               //Postcondition: current = first; previous = null;
            public void reset()
                current = (LinkedListNode<T>) first;
                previous = null;
               //Method to return a reference of the info of the
               //current node in the list and to advance iterator
               //to the next node.
               //Postcondition: previous = current;
               //               current = current.link;
               //               A refrence of the current node
               //               is returned.
            public T next()
                if (!hasNext())
                    throw new NoSuchElementException();
                LinkedListNode<T> temp = current;
                previous = current;
                current = current.link;
                return temp.info;
                //Method to determine whether there is a next
                //element in the list.
                //Postcondition: Returns true if there is a next
                //               node in the list; otherwise
                //               returns false.
            public boolean hasNext()
                return (current != null);
               //Method to remove the node currently pointed to
               //by the iterator.
               //Postcondition: If iterator is not null, then the
               //               node that the iterator points to
               //               is removed. Otherwise the method
               //               throws NoSuchElementException.
            public void remove()
                if (current == null)
                    throw new NoSuchElementException();
                if (current == first)
                    first = first.link;
                    current = (LinkedListNode<T>) first;
                    previous = null;
                    if (first == null)
                        last = null;
                else
                    previous.link = current.link;
                    if (current == last)
                        last = first;
                        while (last.link != null)
                            last = last.link;
                    current = current.link;
                count--;
               //Method to return the info as a string.
               //Postcondition: info as a String object is returned.
            public String toString()
                return current.info.toString();
        } //end class LinkedListIterator
           //Instance variables of the class LinkedListClass
        protected LinkedListNode<T> first; //variable to store the
                                           //address of the first
                                           //node of the list
        protected LinkedListNode<T> last;  //variable to store the
                                           //address of the last
                                           //node of the list
        protected int count;  //variable to store the number of
                              //nodes in the list
           //Default constructor
           //Initializes the list to an empty state.
           //Postcondition: first = null, last = null,
           //               count = 0
        public LinkedListClass()
            first = null;
            last = null;
            count = 0;
           //Method to determine whether the list is empty.
           //Postcondition: Returns true if the list is empty;
           //               false otherwise.
        public boolean isEmptyList()
            return (first == null);
           //Method to initialize the list to an empty state.
           //Postcondition: first = null, last = null,
           //               count = 0
        public void initializeList()
            first = null;
            last = null;
            count = 0;
           //Method to output the data contained in each node.
        public void print()
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            current = first;    //set current so that it points to
                                //the first node
            while (current != null) //while more data to print
                System.out.print(current.info + " ");
                current = current.link;
        }//end print
           //Method to return the number of nodes in the list.
           //Postcondition: The value of count is returned.
        public int length()
            return count;
           //Method to return a reference of the object containing
           //the data of the first node of the list.
           //Precondition: The list must exist and must not be empty.
           //Postcondition: The reference of the object that
           //               contains the info of the first node
           //               is returned.
        public T front()
            return first.info;
            //Method to return a reference of object containing
            //the data of the last node of the list.
            //Precondition: The list must exist and must not be empty.
            //Postcondition: The reference of the object that
            //               contains the info of the last node
            //               is returned.
        public T back()
            return last.info;
           //Returns a copy of objects data in store.
           //This method clones only the references stored in
           //each node of the list. The objects that the
           //list nodes point to are not cloned.
        public Object clone()
            LinkedListClass<T> copy = null;
            try
                copy = (LinkedListClass<T>) super.clone();
            catch (CloneNotSupportedException e)
                return null;
                //If the list is not empty clone each node of
                //the list.
            if (first != null)
                   //Clone the first node
                copy.first = (LinkedListNode<T>) first.clone();
                copy.last = copy.first;
                LinkedListNode<T> current;
                if (first != null)
                    current = first.link;
                else
                    current = null;
                   //Clone the remaining nodes of the list
                while (current != null)
                    copy.last.link =
                            (LinkedListNode<T>) current.clone();
                    copy.last = copy.last.link;
                    current = current.link;
            return copy;
           //Method to return an iterator of the list.
           //Postcondition: An iterator is instantiated and
           //               returned.
        public LinkedListIterator<T> iterator()
            return new LinkedListIterator<T>();
           //Method to determine whether searchItem is in
           //the list.
           //Postcondition: Returns true if searchItem is found
           //               in the list; false otherwise.
        public abstract boolean search(T searchItem);
           //Method to insert newItem in the list.
           //Postcondition: first points to the new list
           //               and newItem is inserted at the
           //               beginning of the list. Also,
           //               last points to the last node and
           //               count is incremented by 1.
        public abstract void insertFirst(T newItem);
           //Method to insert newItem at the end of the list.
           //Postcondition: first points to the new list and
           //               newItem is inserted at the end
           //               of the list. Also, last points to
           //               the last node and
           //               count is incremented by 1.
        public abstract void insertLast(T newItem);
           //Method to delete deleteItem from the list.
           //Postcondition: If found, the node containing
           //               deleteItem is deleted from the
           //               list. Also, first points to the first
           //               node, last points to the last
           //               node of the updated list, and count
           //               is decremented by 1.
        public abstract void deleteNode(T deleteItem);
        public abstract void splitAt(LinkedListClass<T> secondList, T item);
    }And this is the UnorderedLinked Class with the very last method the one being Im stuck on. The SplitAt Method.
    public class UnorderedLinkedList<T> extends LinkedListClass<T>
           //Default constructor
        public UnorderedLinkedList()
            super();
            //Method to determine whether searchItem is in
            //the list.
            //Postcondition: Returns true if searchItem is found
            //               in the list; false otherwise.
        public boolean search(T searchItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            boolean found;
            current = first;  //set current to point to the first
                              //node in the list
            found = false;    //set found to false
            while (current != null && !found) //search the list
                if (current.info.equals(searchItem)) //item is found
                    found = true;
                else
                   current = current.link; //make current point to
                                           //the next node
            return found;
            //Method to insert newItem in the list.
            //Postcondition: first points to the new list
            //               and newItem is inserted at the
            //               beginning of the list. Also,
            //               last points to the last node and
            //               count is incremented by 1.
        public void insertFirst(T newItem)
            LinkedListNode<T> newNode;     //variable to create the
                                        //new node
            newNode =
               new LinkedListNode<T>(newItem, first); //create and
                                           //insert newNode before
                                           //first
            first = newNode;   //make first point to the
                               //actual first node
            if (last == null)   //if the list was empty, newNode is
                                //also the last node in the list
                last = newNode;
            count++;     //increment count
            //Method to insert newItem at the end of the list.
            //Postcondition: first points to the new list and
            //               newItem is inserted at the end
            //               of the list. Also, last points to
            //               the last node and
            //               count is incremented by 1.
        public void insertLast(T newItem)
            LinkedListNode newNode; //variable to create the
                                    //new node
            newNode =
               new LinkedListNode(newItem, null);  //create newNode
            if (first == null)  //if the list is empty, newNode is
                                //both the first and last node
                first = newNode;
                last = newNode;
            else     //if the list is not empty, insert
                     //newNode after last
                last.link = newNode; //insert newNode after last
                last = newNode;      //set last to point to the
                                     //actual last node
            count++;
        }//end insertLast
            //Method to delete deleteItem from the list.
            //Postcondition: If found, the node containing
            //               deleteItem is deleted from the
            //               list. Also, first points to the first
            //               node, last points to the last
            //               node of the updated list, and count
            //               is decremented by 1.
        public void deleteNode(T deleteItem)
            LinkedListNode<T> current; //variable to traverse
                                       //the list
            LinkedListNode<T> trailCurrent; //variable just
                                            //before current
            boolean found;
            if ( first == null)    //Case 1; the list is empty
                System.err.println("Cannot delete from an empty "
                                 + "list.");
            else
                if (first.info.equals(deleteItem)) //Case 2
                    first = first.link;
                       if (first == null)  //the list had only one node
                          last = null;
                       count--;
                else  //search the list for the given info
                    found = false;
                    trailCurrent = first; //set trailCurrent to
                                          //point to the first node
                    current = first.link; //set current to point to
                                          //the second node
                    while (current != null && !found)
                        if (current.info.equals(deleteItem))
                            found = true;
                        else
                            trailCurrent = current;
                            current = current.link;
                    }//end while
                    if (found) //Case 3; if found, delete the node
                        count--;
                        trailCurrent.link = current.link;
                        if (last == current)  //node to be deleted
                                              //was the last node
                           last = trailCurrent;  //update the value
                                                 //of last
                    else
                       System.out.println("Item to be deleted is "
                                        + "not in the list.");
                }//end else
            }//end else
        }//end deleteNode
        public void splitAt(LinkedListClass<T> secondList, T item)
         LinkedListNode<T> current;
         LinkedListNode<T> trailCurrent;
         int i;
         boolean found;
         if (first==null)
        System.out.println("Empty.");
        first=null;
        last=null;
        count--;
        count=0;
         else
              current=first;
              found=false;
              i=1;
              while(current !=null &&!found)
                   if(current.info.equals(item))
                       found= true;
                       else
                            trailCurrent=first;
                            current=first;
                            i++;
              if(found)
                   if(first==current)
                        first.link=first;
                        last.link=last;
                           count--;
                        count=0;
                   else
                        first.link=current;
                        last.link=last;
                        last=null;
                        count = count- i+1;
                        count = i-1;
              } else  {
                  System.out.println("Item to be split at is "
                    + "not in the list.");
                   first=null;
                   last=null;
                   count=0;
        Any help or just advice would be fine. Im not the best at Java, better at VB. Am completely stumped! Thanks so much!

  • Recursively Finding a Node in a Linked List

    I'm trying to find a node recursively in this linked list but keep coming up with an error message - can anyone tell me what is wrong?
         public boolean find (Object obj)
              DonorNode node = new DonorNode(obj);
              DonorNode current = list;
              if (don.equals(current))
                   return true;
              else
                   return find(current.next);
         }

    Please post within code tags (button above the message box).
    Without more information it's hard to say.
    What is list?
    What is don?
    If you don't mind me pointing out:
    A method named find conventionally returns some object it is searching for or null if not found.
    What you have (by that I mean a method returning boolean) is generally named contains (or some other obvious predicate name).
    That being said, if I assume that DonorNodes contain some Object and have getter functions to access those; and that list is a DonorNode representing the head of the list, try something like:public boolean contains(Object o) {
        return contains(o, list);
    private boolean contains(Object o, DonorNode n) {
        if (n.getObject() == o)
            return true;
        if (n.getNext() == null)
            return false;
        return contains(o, n.getNext());
    }Although keep in mind that comparing two Objects using '==' will result in reference only comparison. If you need some other form of comparison you might consider using the equals method (make sure you then implement it in all potentially contained classes) or even narrowing the accepted argument to classes that implement the Comparable interface.
    Hope this helps.

  • How do you change the font in WPC Link List Header ...

    Does any one know how/where to change the font in Web Page Composer on the Link List Header?  I am using the Link List header delivered with the product. 
    It looks like it is pulling arial font but we are adding content in a different font in the paragraphs and want the fonts to be the same.  Is there something I can change in the theme?
    thanks
    Angie.

    You need to go to the
    Content Adminstration/KM Content/etc/wpceditor/css/runtime  and look in the sdn_general.css file.  The controls are all there.  You can rename or create a new style sheet as this will modify all WPC sites.

  • Linked List - nodes

    Hi,
    In a lecture a couple of weeks ago, we began the topic of reference-based lists. I copied the attached
    code off the board. I'm now trying to utilize the code by creating a public class Node. However, the constructors don't seem to make much sense. I was too busy writing down the information to pay much attention at the time. My book doesn't seem to address this...
    1) in the first constructor: item = null; I'm declaring item initially as an integer, but the constructor is trying to attach a null to item. I think the intent is to create a node that initially has both info and link as nulls.
    2) in the third constructor: link = Node; Is this possible? I'm not what this will do.
    And finally, the second and third constructors are using the same name and parameter, so there is a conflict. I don't know how to resolve this.
    Thanks in advance for any help...
    aiki
    public class Node {
              public int info;
              public Node link;
              public Node(){
                   info = null;
                   link = null;
              public Node (int data){
                   info = data;
                   link = null;
              public Node (int data){
                   info = data;
                   link = Node;

    public class Node {
        public int info;
        public Node link;
        public Node(){
            // default constructor does nothing.
            // Therefore info and link will get default values.
            // For Objects this will be null
        public Node (int data){
            info = data;
            // don't initialise link. See above
        public Node (int data, Node node){
            // I think you missed the second parameter
            info = data;
            link = node;
    }

  • Linked List Node assigning

    I have a binary B+tree.
    I have done all the insertion..but I have a major problem as my current node is poiting to the last node I inserted node ...
    In the class I have a parent node
    I want to use this to go back to the root...but I fail..function is called from a tree class
    in the function {
    Node curr = this;
    Node temp= this.parent;
    while(temp!=null) {
    temp= temp.parent;
    if(temp!=null) {
    curr=temp;
    return curr;
    However, this code doesn't work...
    not sure why...
    can anyone help me with this .. Thanks?

    carl33p wrote:
    Might have to fill it manually unless anyone else has an idea.
    ...I have a few ideas:
    - keep the logic from getting input from a user separate from your linked list
    class: it is not the responsibility of a linked list to perform such tasks;
    - create a separate class with a main method that instantiates a linked list
    and gets the user input;
    - don't name one of your classes the same as one of Java's "core" classes. When
    you do "import java.util.*" you might get in trouble. Since you are only storing
    int's in your list, a better name would be "IntLinkedList"
    - create a method called add(int) that is responsible for the addition of new
    nodes;
    - create a private inner class for your Node class: you won't be needing this
    Node outside of your IntLinkedList class, so there's no need for it to be
    "visible" for other classes.
    Here's a skeleton:
    class Test {
        private static int getUserInput() {
            // Prompt the user to enter an integer and when
            // a valid integer is entered, return it.
            return -1;
        public static void main(String[] args) {
            IntLinkedList myList = new IntLinkedList();
            int nodeCount = 5;
            while(nodeCount-- > 0) {
                int input = getUserInput();
                myList.add(input);
            System.out.println("myList = "+myList.toString());
    class IntLinkedList {
        private Node start;
        public IntLinkedList() {
            start = null;
        public void add(int value) {
            Node newNode = new Node(value);
            // Your code here
            // - what to do when 'start' equals null?
            // - and what to do when 'start' does not equal null?
        // more methods
        private class Node {
            int value;
            Node next;
            Node(int v) {
                value = v;
                next = null;
            // more methods
    }

  • Help needed in linked lists...

    I have been working on this computer assignment lately but I still don't understand linked lists yet..I did an assignment on array based implementation and now I am supposed to do the same thing in linked list implementation..
    I need help on how to change this into a linked list implementation..any help would be appreciated. Thank you..below is the code for the array based implementation..the only thing that needs change here is after where is says Array-based implementation of the ADT list.
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Array-based implementation of the ADT list.
    class ListArrayBased {
        private static final int MAX_LIST = 50;
        private Object items[];  // an array of list items
        private int numItems;  // number of items in list
        public ListArrayBased()
        // creates an empty list
             items = new Object[MAX_LIST];
             numItems = 0;
        }  // end default constructor
        public boolean isEmpty()
          return (numItems == 0);
        } // end isEmpty
        public int size()
           return numItems;
        }  // end size
        public void removeAll()
          // Creates a new array; marks old array for
          // garbage collection.
          items = new Object[MAX_LIST];
          numItems = 0;
        } // end removeAll
        public void add(int index, Object item) throws  ListIndexOutOfBoundsException
          if (numItems > MAX_LIST)
            throw new ListException("ListException on add");
        }  // end if
          if (index >= 1 && index <= numItems+1)
            // make room for new element by shifting all items at
            // positions >= index toward the end of the
            // list (no shift if index == numItems+1)
            for (int pos = numItems; pos >= index; pos--) {
              items[translate(pos+1)] = items[translate(pos)];
          } // end for
          // insert new item
          items[translate(index)] = item;
          numItems++;
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
             "ListIndexOutOfBoundsException on add");
          }  // end if
        } //end add
        public Object get(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            return items[translate(index)];
          else 
          {  // index out of range
            throw new ListIndexOutOfBoundsException(
              "ListIndexOutOfBoundsException on get");
          }  // end if
        } // end get
        public void remove(int index) throws ListIndexOutOfBoundsException
          if (index >= 1 && index <= numItems)
            // delete item by shifting all items at
            // positions > index toward the beginning of the list
            // (no shift if index == size)
                for (int pos = index+1; pos <= size(); pos++) {
                    items[translate(pos-1)] = items[translate(pos)];
          }  // end for
          numItems--;    
          else
          {  // index out of range
            throw new ListIndexOutOfBoundsException("ListIndexOutOfBoundsException on remove");
          }  // end if
        } // end remove
        private int translate(int position) {
        return position - 1;
       } // end translate
    }  // end ListArrayBased
    class ListException extends RuntimeException
      public ListException(String s)
        super(s);
      }  // end constructor
    }  // end ListException
    class ListIndexOutOfBoundsException
                extends IndexOutOfBoundsException {
      public ListIndexOutOfBoundsException(String s) {
        super(s);
      }  // end constructor
    }  // end ListIndexOutOfBoundsException

    Could someone check for me if this will work and if it doesn't what I need to do to make it work..Thanks...
    public class ListArrayBasedDriver {
      public static void main(String [] args) {
        ListArrayBased myGroceryList = new ListArrayBased();
        myGroceryList.add(1,"milk");
        myGroceryList.add(2,"eggs");
        myGroceryList.add(3,"butter");
        myGroceryList.add(4,"pecans");
        myGroceryList.add(5,"apples");
        myGroceryList.add(6,"bread");
        myGroceryList.add(7,"chicken");
        myGroceryList.add(8,"rice");
        myGroceryList.add(9,"red beans");
        myGroceryList.add(10,"sausage");
        myGroceryList.add(11,"flour");
        printList(myGroceryList); //print out original List
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("adding juice for 5th item...");
        myGroceryList.add (5, (Object) "juice");  //add juice
        System.out.println("item 5 is: " + myGroceryList.get(5)); //get position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
        System.out.println("removing juice...");
        myGroceryList.remove (5); //remove item at position 5
        printList(myGroceryList);
        System.out.print("numItems is now: " + myGroceryList.size() + "\n");
      public static void printList(ListArrayBased myList)
            //method prints a list, numbering the values,  e.g, "1.  milk" .... "5.  juice".... etc.
            int i;
            for(i=1; i <= myList.size(); i++)
                String tempString = new String((String)myList.get(i));
                System.out.println(i+" "+ tempString);
    // Linked List-based implementation of the ADT list.
    class ListNode
         //class to represent one node in a list
         class ListNode
              //package access members; List can access these directly
              Object data;
              ListNode nextNode;
              //contructor creates a ListNode that refers to object
              ListNode( Object object)
                   this( object, null );
              } //end ListNode one-argument constructor
              //constructor creates ListNode that refers to
              // Object and to the next ListNode
              ListNode ( Object object, ListNode node)
                   data = object;
                   nextNode = node;
              // end ListNode two-argument contructor
              //return reference to data in node
              Object getObject()
                   return data; // return Object in this mode
              //return reference to next node in list
              ListNode getNext()
                   return nextNode; // get next node
              } // end method getNext
    } //end class ListNode
    //class List Definition
    public class List
         private ListNode firstNode;
         private ListNode lastNode;
         private String name; // string like " list " used in printing
         //contructor creates empty List with " list " as the name
         public List()
              this(" list ");
         } //end List no-arguement constructor
    //contructor creates an empty list with a name
    public List( String listName )
         name = listname;
         firstNode = lastNode = null;
    } //end List no-arguement contructor
    //insert Object at front of List
    public void insertAtFront ( object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = lastNode = newListNode( insertItem );
         else // firstNode refers to new node
              firstNode = new ListNode ( insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insert AtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and lastNode refer to same object
              firstNode = new ListNode ( insertItem );
         else // firstNode refers to new node
         firstNode = new ListNode (insertItem, firstNode );
    } // end method insertAtFront
    // insert Object at end of List
    public void insertAtBack ( Object insertItem )
         if ( isEmpty() ) //firstNode and LastNode refer to same Object
              firstNode = lastNode = new ListNode ( insertItem );
         else // lastNode = lastNode.nextNode = new ListNode ( insertItem );
    } // end method insertAtBack
    //remove first node from List
    public Object removeFromFront() throws EmptyListException
         if( isEmpty() ) //throw exception if list is empty
         throw new EmptyListException( name );
         object removedItem = firstNode.data; //retrieve data being removed
    // update references firstNode and lastNode
    if (firstNode == lastNode )
         firstNode =lastNode = null;
    else
         firstNode = firstNode.nextNode;
         return removedItem; // return removed node data
    } //end method removeFromFront
    //remove last node from List
    Public Object removeFromBack() throws EmptyListException
         If ( isEmpty() ) // throw exception if list is empty
              throw new EmptyListException( name );
         Object removedItem = lastNode.data; // retrieve data being removed
         // update references firstNode and lastNode
         If ( firstNode == lastNode )
              firstNode = lastNode = null;
         else // locate new last node
              ListNode current = firstNode;
              // loop while current node does not refer to lastNode
              while ( current.nextNode != lastNode )
                   current = current.nextNode;
              lastNode = current; // current is new lastNode
              current.nextNode = null;
         } // end else
         return removedItem; // return removed node data
    } // end method removeFromBack
    // determine whether list is empty
    public boolean isEmpty()
         return firstNode == null; // return true if list is empty
    }     // end method isEmpty
    //output List contents
    public void print()
         if (isEmpty() )
              System.out.printf(�Empty %s\n�, name );
              return;
         System.out.printf(�The %s is: �, name );
         ListNode current = firstNode;
         //while (current != null )
              System.out,printf(�%s �, current.data );
              current = current.nextNode;
         } //end while
         System.out.println( �\n� );
    } //end method print
    } end class List

Maybe you are looking for

  • Can VC print all data in a table?

    Hello!   Can VC print all data in a table? Best Reagrds! csquare.

  • Problem in RTF template

    Hi all, I use Bi publisher version (11.1.6 ) First Question : What is the best template type for making operational reports not statistical report ( RTF template or PDF template or others ) ? -- Second Question : when i try to make report template us

  • I can't email pdf's from Adobe professional 11.0.5 using default mail client Microsoft Outlook 2013 32 bit

    I am using Adobe Professional v 11.0.5 and have moved from Microsoft Outlook 2010 to 2013 now I am unable to e-mail pdfs directly to local configured mail client. As a work around I have to save file to desktop and place as an attachment in newly com

  • CO-PA Characteristic hierarchies in reports

    Hi Experts, I am aware that characteristic hierarchies can be used in CO-PA reports by specify in the hierarchy dialog box while defining characteristics in reports - but this is during creating/changing the reports My requirement is that I should be

  • URGENT : can't boot !!!!!

    Hello, I have a white macbook 2.0ghz and after my last restart , i couldn't boot it back So here's what happened : I was in my little room on my campus doing my paper and concentrating every fiber of brain on the kant's problem of sublime jugement .