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.

Similar Messages

  • Replace node in a linked list.

    Hello everyone,
    Im trying to replace a node with the following method :
    @Override
         public boolean replace(Object oneThing) {
              Node aNode = find(oneThing); // gets a node previous to oneThing
              if(aNode == null)
                   return false;
              oneThing = aNode.next.next;
              aNode.next = (Node) ((Copyable) oneThing).copy();
              return true;
         }I keep getting this error and dont know how to fix it or what im doing wrong:
    Exception in thread "main" java.lang.ClassCastException: myContainers.List$Node cannot be cast to myUtils.CopyableAny help is greatly appreciated.

    Nevermind I got It! thanks

  • Replacing nodes in a linked list

    Hello there, i was having problems replacing all nodes of a specific value to another value, andi have no idea what i was doing wrong. this is what i had:     public void replace(int oldVal, int newVal) {
             IntNode traveller = front;
             if (traveller == null){
                  System.out.println("No list exists");
             } else {         
                  while (traveller != null){
                       if (traveller == oldVal) {
                            traveller = newVal;
                       traveller = traveller.next;
        }I seem to be getting some kind of syntax error on "if (traveller == oldVal) " and another error on "traveller = newVal;"
    Any idea on what I'm doing wrong?

    vexity wrote:
    well i didn't run the program Yeah, I know, because you have syntax errors. You can get descriptive messages for those sytax errors that you can copy and paste here.
         Incompatible operand types IntList.IntNode and int
         Type mismatch: cannot convert from int to IntList.IntNode
         at IntList.replace(IntList.java:157)
         at IntListTest.dispatch(IntListTest.java:84)
         at IntListTest.main(IntListTest.java:25)
    Yeah, like that. That's what we want to see.
    But as I already told you, the problem is that you're trying to mix ints and IntNodes.
    What should i do to solve this problem?Use ints where appropriae, IntNodes where appropriate, and convert between the two when you need to. You do know how to create an IntNode from an int, and how to get an int out of an IntNode, right?

  • Recursion using a linked list

    I am confused at how to make a linked list using recursion. I've been looking at the syntax and examples from the web for the past couple hours, but all seem to be based on an empty .java file. I need to put it in my code somehow. here's the code segment:
    public static boolean RecursiveTest (String s, int start, Node n) {
    // The linked list
    Node<char> bracket = new Node<char>();
    int size = s.length();
    char v = s.charAt(start);
    //String sElement = parens.top();
    boolean isGood = true;
    // ending "ifs"
    if (size == 0) { System.out.println("empty string");  return false; }
    if (start == size) return isGood;
    if (s.charAt(start) == '(' || s.charAt(start) == '[' ||
              s.charAt(start)== '{') {
    v.Push(sChar);
    System.out.println(sChar);
    return RecursiveTest(start+1, s.charAt(start));
    else if (sChar.equals(")") && sElement.equals("(")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals("]") && sElement.equals("[")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals("}") && sElement.equals("{")) {
    parens.Pop();
    System.out.println(sChar);
    return RecursiveTest(start+1);
    else if (sChar.equals(")") && !sElement.equals("(")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else if (sChar.equals("]") && !sElement.equals("[")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else if (sChar.equals("}") && !sElement.equals("{")) {
    System.out.println("bad");
    isGood = false;
    return isGood;
    else return RecursiveTest(start+1);
    } // end of RecursiveTest
    I'm passing a string, 0, and a new node (i dunno about the last one there), from an above main class.
    This code is wrong, i know, but it's all I got done so far. How would I be able to make a linked list inside this method?

    No one knows how to do a linked list inside a recursive method?Yes we do, but you have to realize that a list (whether it be a linked list
    or an array list or whatever) has nothing to do with recursion per se.
    If that list has to keep track of some state it certainly mustn't be created
    within that recursive method as a local variable. And (see my previous
    reply), what do you need recursion for? Counting and pairing brackets
    can easily be done using an iterative method where the list keeps track
    of the last seen left bracket (of any type).
    kind regards,
    Jos

  • Alphabetizing a linked list, HELP!

    To all:
    Firstly, I'm not looking for someone to do my assignment for me. I just need a push in the right direction...
    I need to create a linked list that contains nodes of a single string (a first name), but that list needs to be alphabetized and that's where I am stuck.
    I can use an iterator method that will display a plain-old "make a new node the head" linked list with no problem. But I'm under the impression that an iterator method is also the way to go in alphabetizing this list (that is using an iterative method to determine the correct place to place a new node in the linked list). And I am having zero luck doing that.
    The iterator method looks something like this:
    // ---- MyList: DisplayList method ----
    void DisplayList()
    ListNode p;
    for (ResetIterator(); (p = Iterate()) != null; )
    p.DisplayNode();
    // ---- MyList: ResetIterator method ----
    void ResetIterator()
    current = head;
    // ---- MyList: Iterate method ----
    ListNode Iterate()
    if (current != null)
    current = current.next;
    return current;
    Can I use the same iterator method to both display the final linked list AND alphabetize my linked list or do I need to create a whole new iterator method, one for each?
    Please, someone give me a hint where to go with this. I've spent something like 15 hours so far trying to figure this thing out and I'm just stuck.
    Thanks so much,
    John
    [email protected]

    I'll try and point you in the right direction without being too explicit as you request.
    Is your "linked list" an instance of the Java class java.util.LinkedList or a class of your own?
    If it is the Java class, then check out some of the other types of Collections that provide built-in sorting. You should be able to easily convert from your List to another type of Collection and back again to implement the sorting. (hint: you can do this in two lines of code).
    If this is your own class and you want to code the sort yourself, implement something simple such as a bubble sort (should be easy to research on the web).
    Converting to an array, sorting that and converting back is another option.
    Good Luck.

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

  • Linked List trouble

    //I need to add a header node into this Linked list class and
    // i dont understand it. can anyone give me a few pointers.
    // This is the orginal code. What im trying to figure out is below.
    public abstract class LinkedList implements ListInterface
    protected class ListNode
    // Used to hold references tolist nodes for the linked list implementation
    protected Listable info; // the info in a list node
    protected ListNode next; // a link to the next node on the list
    protected ListNode list; // reference to the first node on the list
    protected int numItems; // Number of elements in the list
    protected ListNode currentPos; // Current position for iteration
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list = null;
    currentPos = null;
    public boolean isFull()
    // Determines whether this list is full.
    return false;
    public int lengthIs()
    // Determines the number of elements on this list.
    return numItems;
    public abstract boolean isThere (Listable item);
    // Determines if element matching item is on this list.
    public Listable retrieve (Listable item)
    // Returns a copy of the list element with the same key as item.
    ListNode location = list;
    boolean found = false;
    while (!found)
    if (item.compareTo(location.info) == 0) // if they match
    found = true;
    else
    location = location.next;
    return location.info.copy();
    public abstract void insert (Listable item);
    // Adds a copy of item to this list.
    public void delete (Listable item)
    // Deletes the element of this list whose key matches item�s key.
    ListNode location = list;
    // Locate node to be deleted.
    if (item.compareTo(location.info) == 0)
    list = list.next; // Delete first node.
    else
    while (item.compareTo(location.next.info) != 0)
    location = location.next;
    // Delete node at location.next.
    location.next = location.next.next;
    numItems--;
    public void reset()
    // Initializes current position for an iteration through this list.
    currentPos = list;
    public Listable getNextItem ()
    // Returns copy of the next element in list.
    Listable nextItemInfo = currentPos.info.copy();
    if (currentPos.next == null)
    currentPos = list;
    else
    currentPos = currentPos.next;
    return nextItemInfo;
    //now heres the part i dont get i need to make list point to a new
    // node say HeaderNode. Now wouldnt just...
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list.next = HeaderNode; //....this line do the trick???
    currentPos = null;
    I know that i cant use any insert methods to put it in, so what else could i possibly do?

    bump

  • Implementing my own linked lists...aiiieee!

    Hi,
    I'm trying to implement my own linked list structure oftype String. It will eventually go to form a simple text editor, with each line of a file being loaded into its own String node.
    However, im having problems implementing the list itself :)
    So far ive got the file to read in succesfully, but now im stuck...how do i load up a line into a new node? and what about the head/tail nodes, they just confuse me! Do i have to write a seperate 'List' class and create an object of that, much like the LinkedList class with Java?
    Any help or a nudge in the right direction would be appreciated,
    TIA
    andrew
    PS code below ...
    =================================
    =================================
    import java.io.*;
    import java.util.*;
    class Editor {
    public static void main(String[] args) {
    ///LOAD UP THE TEXT FILE//////////////////////////////////////
         String file = "s.txt";
         String line;
         System.out.println(System.in);
         //testing here...
    StringNode alist = new StringNode(null,null);
         try{
              FileReader FR = new FileReader(file);
              BufferedReader BR = new BufferedReader(FR);
              while ( (line = BR.readLine()) != null ){
                   alist.addNodeAfter(line);
                   System.out.println(line);
                   }//while
         }//try
         catch(IOException e){
              System.out.println(file + " not found");
         }//catch
    ///COMMANDS///////////////////////////////////////////////////
    //text editor commands to be input via command line type console. how to grab inputs on return?
    }//main
    }//Editor
    //code to create a node...but now what?
         class StringNode
         private String data;
         private StringNode link;
         // constructor for initialisation
         public StringNode(String initialData, StringNode initialLink)
              data = initialData;
              link = initialLink;
         // accessor method to get the data from this node
         public String getData( )
              return data;
         // accessor method to get a reference to the next node after this node.
         public StringNode getLink( )
              return link;
         // modification method to set the data in this node.
         public void setData(String newData)
              data = newData;
         // modification method to set the link to the next node after this node
         public void setLink(StringNode newLink)
              link = newLink;
         // add a new node after this node
         public void addNodeAfter(String item)
              link = new StringNode(item, link);
         // modification method to remove the node after this node.
         public void removeNodeAfter( )
              link = link.link;
         // compute the number of nodes in a linked list
         public static int listLength(StringNode head)
              StringNode cursor;
              int answer;
              answer = 0;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   answer++;
              return answer;
         // print the nodes in a linked list
         public static void listPrint(StringNode head)
              StringNode cursor;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   System.out.println(cursor.getData());
         // print the nodes in a linked list skipping dummy node at head
         public static void listPrint2(StringNode head)
              StringNode cursor;
              for (cursor = head.link; cursor != null; cursor = cursor.link)
                   System.out.println(cursor.getData()+" ");
         // search for a particular piece of data in a linked list
         public static StringNode listSearch(StringNode head, String target)
              StringNode cursor;
              for (cursor = head; cursor != null; cursor = cursor.link)
                   if (target == cursor.data)
                        return cursor;
              return null;
    }

    You wouldn't by any chance be doing computer science at Cardiff university would you and have been given this as an assignment?

  • Links list to open in new tab

    I have created a links list and added that webpart to a page in office 365 for sharepoint. When the user clicks on a links it needs to be opened in new tab how to impletement.
    I tried with javascript content editor webpart but it is removing  the  scroll bar of the page.
    Please let me know. many thanks in advance
    Regards,
    Chaitanya

    Hi Chaitanya,
    May check this article to find the similar code in Links list web part with SharePoint Designer, add the attribute target="_blank" within the code, then check results.
    http://365.webbrewers.com/blog/Lists/Posts/Post.aspx?ID=9
    Thanks
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Implementation of Linked List class

    I am trying to implement the Linked List class for one week, but I couldn't figure it out. If you know, please let me know.

    Here is an example of a linked list. Hope that will help.
    // define a node of a linked list
    public class Node
    public int data; // point to data
    public Node next; // pointer to next node or point to null if end of list
    // listTest1
    public class ListTest1
    public static void main(String[] args)
    Node list;
    list = new Node();
    list.data = 3;
    list.next = new Node();
    list.next.data = 7;
    list.next.next = new Node();
    list.next.next.data = 12;
    list.next.next.next = null;
    Node current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();
    // other listnode
    public class ListNode
    public int data;
    public ListNode next;
    public ListNode()
    // post: constructs a node with data 0 and null link
    this(0, null);
    public ListNode(int value)
    // post: constructs a node with given data and null link
    this(value, null);
    public ListNode(int value, ListNode link)
    // post: constructs a node with given data and given link
    data = value;
    next = link;
    Contents of ListTest2.java
    public class ListTest2
    public static void main(String[] args)
    ListNode list = new ListNode(3, new ListNode(7, new ListNode(12)));
    ListNode current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();

  • Linked lists help... how exactly is this a NullPointerException?

    So I have a linked list class with variables head and tail both initialized to "null", with variables for size, declare, and traveler (not really relevant to this though). We have to create methods to manipulate said list.
    For a test I declared an instance of this linked list:
    static SinglyLinkedList list = new SinglyLinkedList();One of the methods we have to create is an append method, here's the code for that:
    public void append(Object dataToAdd)
              if(head == null & tail == null)
                   head = new Node(dataToAdd, null);
                   tail = head;
              else
                   tail.next = new Node(dataToAdd, null);
                   tail = tail.next;
         }Testing it with...
    list.append("A");Gives null pointer exceptions at the if statement in the append method as well as at the list.append line. But why? What is exactly pointing to null?

    Ah... I didn't think of head not being null but tail being null.
    I initiated the traveler node in the linked list class to head.
    then I added this in between the if and else statements I had:
    else if(head != null & tail == null)
                   while(traveler.next != null)
                        traveler = traveler.next;
                   tail = traveler;
                   tail.next = new Node(dataToAdd, null);
                   tail = tail.next;
                            }But it's still giving me the same errors.
    Edited by: klawson88 on Feb 12, 2009 12:32 AM

  • Appending in linked list

    Hello there, my question is regarding linked lists.
    I'm not sure why but I have some confusion about 'append' or rather the definition of it
    is appending a node to a linked list the same as adding a node to the end of the linked list?
    If so would it be possible to do this by making a new node (ie. newNode) and making tail = newNode ?

    vexity wrote:
    do i do a tail.next = newNode and then tail = newNode ?Try it and see what happens.

  • Linked list troubles

    How do i put a headernode into this constructor?
    protected class ListNode
    // Used to hold references tolist nodes for the linked list implementation
    protected Listable info; // the info in a list node
    protected ListNode next; // a link to the next node on the list
    protected ListNode list; // reference to the first node on the list
    protected int numItems; // Number of elements in the list
    protected ListNode currentPos; // Current position for iteration
    public LinkedList()
    // Creates an empty list object.
    numItems = 0;
    list = null;
    currentPos = null;

    You mean...
    public LinkedList(ListNode nodeHeader)
      numItems = 0;
      list = nodeHeader;
      currentPos = null;

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

  • Write two functions to find the the number of elements in a linked list?

    I am trying to Write two functions to find the the number of elements in a linked list. One method using recursion and One method using a loop...
    //The linked List class is Represented here.
    public class lp {
    public int first;
    public lp rest;
    public lp(int first1, lp rest1)
    first = first1;
    rest = rest1;
    The program i wrote so far is
    import java.util.*;
    import linklist.lp;
    public class listCount{
    //loop function
    public static void show_list(lp list)
    int counter = 0;
    while(list != null)
    list = list.rest;
    counter++;
    System.out.println ("length computed with a loop:" + counter);
    //recursive function
    public static int recursive_count(lp list)
    if (list.first == null)
    return 0;
    else
    return recursive_count(list.rest) + 1;
    //main method
    public static void main (String args[])
    lp list1 = new lp(1, new lp(2, new lp(3, null)));
    show_list(list1);
    System.out.println("length computed with a recursion:" +
    recursive_count(list1));
    at the if (list.first == null) line i get the error " incomparable types:
    int and <nulltype>" I know this is a beginners error but please
    help...What should I do?

    byte, char, short, int, long, float, double, and boolean are primitives, not objects. They have no members, you cannot call methods on them, and they cannot be set to or compared with null.

Maybe you are looking for