Re: I got it working, but have trouble reversing the list
From: D. Beckham (lekhanh88_at_earthlink.net)
Date: 05/31/04
- Next message: Jo Vermeulen: "Re: adding a condition to the enhanced for loop"
- Previous message: iamfractal_at_hotmail.com: "JMenu help"
- Next in thread: Roedy Green: "Re: I got it working, but have trouble reversing the list"
- Reply: Roedy Green: "Re: I got it working, but have trouble reversing the list"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 31 May 2004 21:57:57 GMT
Thanks. I fixed the link list and was able to print out all the elements.
However, I spend 2 hrs trying to reverse the list. I made many changes and
always get a null pointer exception when the ReverseList method is called.
Would you please help me with an algorithm to reverse the list?
public class TestNode
{
private static DLLNode head = null;
private static DLLNode tail = null;
//private static int count = 0;
private static DLLNode [] curNode = new DLLNode [2];
public static void main(String[] args)
{
DLLNode hNode = new DLLNode(null, null, null); //create head node
DLLNode tNode = new DLLNode("Three", null, hNode); //create tail node
DLLNode cNode = new DLLNode("One"); //insert cNode after head
DLLNode cNode1 = new DLLNode("Two"); //insert cNode1 after cNode
//Create doubly-link nodes
hNode.setNext(cNode);
cNode.setPrev(hNode);
cNode.setNext(cNode1);
cNode1.setPrev(cNode);
cNode1.setNext(tNode);
tNode.setPrev(cNode1);
//assign newly created objects to global variables
head = hNode;
tail = tNode;
curNode[0] = cNode;
curNode[1] = cNode1;
//print nodes
DLLNode p = head.getNext();
printList(p);
//reverse list
printList(reverseList(head));
}
public static void printList (DLLNode head) //print list
{
if(head.getNext() == null)
{
System.out.println("List is empty");
return;
}
while(head != null)
{
System.out.println(head.getElement());
head = head.getNext();
}
}
/////////////////////I have trouble with this particular
method/////////////////////////////////////////////
public static DLLNode reverseList (DLLNode head) //returns the head of
reversed list
{
DLLNode temp = null;
DLLNode p = head;
while(p != null){
temp = p.getNext();
p.setElement(p.getNext());
p.setPrev(temp);
}
return p;
}
- Next message: Jo Vermeulen: "Re: adding a condition to the enhanced for loop"
- Previous message: iamfractal_at_hotmail.com: "JMenu help"
- Next in thread: Roedy Green: "Re: I got it working, but have trouble reversing the list"
- Reply: Roedy Green: "Re: I got it working, but have trouble reversing the list"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|