Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Linked list copy constructor

  1. Oct 17, 2011 #1
    having trouble with a copy constructor for a linked list. I know what im doing wrong im just not too sure how to fix it. First i'll show my node class and the copy constructor that im working on.


    node class:

    Code (Text):
    class CharNode
    {
       
       private char letter;
       private CharNode next;
       
       public CharNode(char ch, CharNode link)
        {
            letter = ch;
            next = link;
       }
         
       public void setCharacter(char ch)
        {
            letter = ch;
        }
       
       public char getCharacter()
        {
            return letter;
        }
       
        public void setNext(CharNode next)
        {
            this.next = next;
        }
       
       public CharNode getNext()
        {
            return next;
        }
       
    }

    and the copy constructor

    Code (Text):
      // copy constructor  
       public CharList(CharList l)
        {
            CharNode pt = head;
            CharNode newList = new CharNode();
           
            while(pt.getNext() != null)
            {
                newList.setCharacter() = l.getCharacter();
                newList.setNext() = l.getNext();
            }
        }
    the constructor is in a class called CharList and the only variable in the class is a CharNode head which represents the pointer.

    the problem is that the CharNode constructor takes in a char and a CharNode but in my constructor im passing in nothing.

    would it be a good idea to create the new CharNode inside the while loop or am i just doing it the wrong way?
     
  2. jcsd
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted