Been working on this for 2 hours non stop.
Can't seem to figure out exactly what's the problem. Perhaps I'm taking a wrong approach to this problem.
Right, I need to copy a singly linked list to another new list. Can use any method EXCEPT RECURSION.
Here's the code so far:
public class copyList
{
public static void main (String args[])
{
new copyList ();
}
String x;
private node head1 = new node ();
private node tail1 = head1;
private node head2 = new node ();
private node tail2 = head2;
public copyList ()
{
//LIST 1
head1.w = "Apples";
tail1.next = new node ();
tail1 = tail1.next;
tail1.w = "Chips";
tail1.next = new node ();
tail1 = tail1.next;
tail1.w = "Milk";
tail1.next = new node ();
tail1 = tail1.next;
tail1.w = "Paper";
tail1.next = new node ();
tail1 = tail1.next;
tail1.w = "Pens";
tail1.next = new node ();
tail1 = tail1.next;
//----------------------------------------------------------------
//keep popping into new list
node current2 = head2;
int count = 0;
while (current2.next != null)
{
x = "";
//so it adds the first value to head when count = 0; but after incrementing, it should add to the tail.
if (count == 0)
{
pop ();
addToHeadNew ();
count++;
current2 = current2.next;
}
else
{
pop ();
addToTailNew ();
current2 = current2.next;
}
}
//----------------------------------------------------------------
//Print both lists
print (head1);
System.out.println ("");
print (head2);
}
//add to the head of the list. Only for the first value.
public void addToHeadNew ()
{
node temp = new node ();
temp.w = x;
temp.next = head2;
head2 = temp;
}
//add to the tail of the list
public void addToTailNew ()
{
tail2.w = x; //the value stored in pop
tail2.next = new node ();
tail2 = tail2.next;
}
//store the value to be copied
public void pop ()
{
//check value but dont delete link.
node temp = head1;
if (temp.w != null)
{
temp = head1;
x = temp.w; //to be used later
temp = temp.next;
}
}
//print
public void print (node head)
{
node current = head; //keeps track of our current position. like a counter.
int count1 = 0;
while (current.next != null)
{
System.out.println (count1 + 1 + ". " + current.w);
current = current.next;
count1++;
}
}
}
Any help is appreciated. I just want this headache to go away...