View Single Post
Old Jun 8th, 2007, 6:53 AM   #1
mrynit
Hobbyist Programmer
 
mrynit's Avatar
 
Join Date: Mar 2006
Location: WA, USA
Posts: 342
Rep Power: 3 mrynit is on a distinguished road
Send a message via AIM to mrynit Send a message via MSN to mrynit Send a message via Yahoo to mrynit Send a message via Skype™ to mrynit
reversing doublely linked list

To reverse the list i need to "flip" the prev next "pointers" for each node and moving the head pointer. i keep doing this until the head pointer is null. the code i have is half give half done by me. the method to reverse reversedList was give. i dont understand what/how the dot notation is doing inside the for loop. I dont have to worry about proper OOP on this one so im guessing that has to do some thing with it.

public class TestDLLNode 
{
	static DLLNode head, curr, prev, next, trail = null;
	
	public static void main(String[] args) 
	{
		//make first node. value with no connections
		curr = new DLLNode("one");
		prev =curr;
		head = curr;
		
		//creat a new node with the value of "two" and stroes it in curr
		//no connections made yet
		//overwrite curr("one") to new object curr("two")
		curr = new DLLNode("two");
		
		//establish the link to prev, connecting two to one
		//set the previous _pointer_ of the current node ("two") to point to the 
		//previous node object ("one")
		//(current_obj).setPrevious((last_node_obj));
		//curr here means ("two")
		//prev here means ("one")
		curr.setPrevious(prev);
		
		//link "one" to  "two"
		//prev here means ("one")
		//curr here means ("two")
		prev.setNext(curr);
		
		//copy curr node to prev nod b/c will become the new node
		//prev will hold the "old" node for the next round of assigning
		prev = curr;
		
		/* **third***/
		curr = new DLLNode("three");
		curr.setPrevious(prev);
		prev.setNext(curr);
		prev = curr;
		
		//print list
		printList(head);
		
		//print list
		printList(reversedList(head));		
		
	}//end main
	
	public static void printList(DLLNode head)
	{
		System.out.print("[");
		while(head != null)
		{
			System.out.print(head.getValue() + " " );
			head = head.getNext();
		}
		System.out.print("]\n");
	}

	public static DLLNode reversedList(DLLNode head)
	{		
		curr = head;
		prev = null;
		
		while(curr != null)
		{
			next = curr.next;
			curr.next = prev;
			curr.prev = next;
			prev = curr;
			curr = next;
		}
		return prev;
	}
}//end class

public class DLLNode 
{
	private String nodeValue;
	public DLLNode prev;
	public DLLNode next;
	
	public DLLNode(String item)
	{
		nodeValue = item;
		this.prev = null;
		this.next = null;
	}
	
	public void setPrevious(DLLNode prev)
	{
		this.prev = prev;
	}
	
	public void setNext(DLLNode next)
	{
		this.next = next;
	}
	
	public String getValue()
	{
		return nodeValue;
	}
	
	public DLLNode getNext()
	{
		return next;
	}
	
	public DLLNode getPrev()
	{
		return prev;
	}
}
__________________
i dont know much about programming but i try to help
mrynit is offline   Reply With Quote