I need to use a linked list to create a list, make a copy of the list, then reverse the list and pull out any duplications. I am having trouble reversing my list and not sure how to pull out the duplicates. Do I need more methods and should I use an array? If I add an array I am not sure how to implement that. Thanks in advance for any help.
public class ListElement2
{
private ListElement2 next;
private Object data;
//default constructor
public ListElement2()
{
next = null;
data = null;
}
//parameterized constructors
public ListElement2(Object d)
{
next = null;
data = d;
}
public ListElement2(Object d, ListElement2 lnk)
{
next = lnk;
data = d;
}
//setter
public void setData(Object d)
{
data = d;
}
public void setNext(ListElement2 lnk)
{
next = lnk;
}
//getters
public Object getData()
{
return data;
}
public ListElement2 getNext()
{
return next;
}
//display list method
public void displayList()
{
ListElement2 lnk = this;//keep this head reference
while(lnk!= null)//this is the end of the list
{
System.out.print(lnk.getData()+ " ");
lnk = lnk.getNext();//increment list
}
}
public int count(ListElement2 head)
{
int numNodes = 0;
ListElement2 lnk = head;
while(lnk!=null)
{
numNodes++;
lnk=lnk.getNext();
}
return numNodes;
}//end count
public void addNodeAfter(Object element)
{
next = new ListElement2(element, next);
}
public static ListElement2 listCopy(ListElement2 source)
{
ListElement2 copyHead;
ListElement2 copyTail;
//Handle special case of an empty list
if (source == null)
return null;
//make the first node for the new list
copyHead = new ListElement2(source.data, null);
copyTail = copyHead;
//make the rest of the nodes for the list
while (source.next != null)
{
source = source.next;
copyTail.addNodeAfter(source.data);
copyTail = copyTail.next;
}
//return head reference for new list
return copyHead;
}
____________________________________________________
public class ListElementDemo2 {
public static void main(
String args[])
{ //Data list
ListElement2 head = new ListElement2(2);
ListElement2 one = new ListElement2(4);
ListElement2 two = new ListElement2(6);
ListElement2 three = new ListElement2(8);
ListElement2 four = new ListElement2(6);
ListElement2 five = new ListElement2(8);
ListElement2 current = head;//put head in a safe
current.setNext(one);
current = current.getNext();
current.setNext(two);
current = current.getNext();
current.setNext(three);
current = current.getNext();
current.setNext(four);
current = current.getNext();
current.setNext(five);
//display contents of the list
head.displayList();
System.out.println();
int num=head.count(head);
System.out.println("---------------");
//display how many nodes in the list
System.out.println("Number of nodes: "+num);
System.out.println("---------------");
//making a copy of the list
ListElement2 newList;
newList = ListElement2.listCopy(head);
System.out.println("Results of the copy method: ");
newList.displayList();
System.out.println();
System.out.println("---------------");
}
}