PDA

View Full Version : Urgent Help Needed.. reverse a singularly linked-list


karthikvardhan
01-13-2009, 06:11 PM
Write a function to reverse a singularly linked-list in the language you are most proficient.

Here is the code structure:

class Node
{
//**** LINK TO THE NEXT NODE *****//
Node next;

//**** CONTENT OF THIS NODE *****//
BigContent content1;
BigContent content2;
// … there are many more members here

};

// Feel free to add helper functions if needed here.

// This method accepts a linked list
// and returns the reversed list
Node Reverse( Node head )
{
// Please put your implementation in any language here
}

oracleguy
01-13-2009, 07:00 PM
1.5) No homework assignments - Do not post your entire homework assignment and request that other members do it for you. This is considered cheating, and your thread may even be used by your school to prove your guilt. Now, you may ask for advice or help on a specific aspect of your assignment that you're having trouble with. Use common sense as far as what's acceptable in terms of soliciting help with homework assignments.

We can help you write this function but will not do all work for you.

Fou-Lu
01-13-2009, 11:54 PM
Coding is one thing, but we can give you a few pointers and any help on really specific issues.
That being said, since you're method returns a Node, that leads me to believe you can construct a new list on the fly as opposed to actually reversing the original.
Use a shadow stack and standard iteration of a cloned list. Shift off list, push onto stack. When cloned list is empty, iterate stack and pop off, and push into a new list. Nice and reversed. Stack can be a custom or built stack, or even an array (which will need resizing, so I'd avoid unless you're keeping a count of nodes).
If you need to reverse the original list (which I wouldn't typecast a return result of a node or list), it takes a little more work. Previous, current, next and shadow usage.

I think that should be sufficient hinting for you on this without actually telling you how to do it. Once you're into Doubly linked list usage, this is way easer since you can directly call a previous on a current node.

ralph l mayo
01-14-2009, 07:54 PM
If you know C[++] at all this problem is easier to solve with the assumption that 'next' is a pointer to Node rather than a Node value. In fact it's only a couple lines. Think about what the list looks before (with -> standing for the next poiner): A->B->C->D and what it needs to look like after: D->C->B->A.

Good luck with the job hunt!