Results 1 to 3 of 3
  1. #1
    fultonwilcox is offline Member
    Join Date
    Sep 2012
    Posts
    7
    Rep Power
    0

    Default popping the last element in a linked list

    Hi, I'm trying to implement a stack right now. I have added the proper functions for peek() and push(), but I cannot figure out how to traverse a linked list. I know it can be done with an iterator, but I don't want to approach it using that. It'd be nice to learn, but I was trying to do it the same way I did in C++.

    Is it possible to traverse a linked list in the implementation with a Node that i allocated memory for? or will it always be a reference to the head node, and will never refresh?

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,458
    Rep Power
    25

    Default Re: popping the last element in a linked list

    how to traverse a linked list
    Follow the nextNode chain.

    Is it possible to traverse a linked list in the implementation ...
    Can you post some code that shows the problem you are having?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    fultonwilcox is offline Member
    Join Date
    Sep 2012
    Posts
    7
    Rep Power
    0

    Default Re: popping the last element in a linked list

    sorry, i fixed it. I guess I was doing it wrong in the first place. It seemed as if the travel Node was stuck at the end and wouldn't let me pop every time, but it had worked. Thanks anyways!
    Java Code:
    	public Object pop()
    	{
    		Object obj;
    		Node travel = new Node();
    		travel = head;
    		// should reach 1 before the end
    		for(int i = 0 ; i < size-1 ; i++ )
    			travel = travel.next;
    		size--;
    		obj = travel.data;
    		travel.next = null;
    		return obj;
    	}

Similar Threads

  1. Removing first element in a linked list do not work
    By Pojahn_M in forum New To Java
    Replies: 4
    Last Post: 05-12-2012, 01:57 PM
  2. Linked List: Removing Largest Element Using Iterator
    By helloworld12 in forum New To Java
    Replies: 2
    Last Post: 05-08-2011, 05:28 AM
  3. Replies: 4
    Last Post: 02-21-2011, 09:34 AM
  4. Linked list inside a linked list
    By viperlasson in forum New To Java
    Replies: 5
    Last Post: 07-26-2010, 11:15 PM
  5. Convert Linked List Object element to String
    By CirKuT in forum New To Java
    Replies: 2
    Last Post: 12-13-2008, 05:22 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •