Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using VS 2010. In my application, I have a linked list, containing a few integers. I want to be able to link the last item in the list to the first item in the list, so that when I loop through the list, it should run continuously until stopped by event (like a circular motion, it just keeps on going)

I know that with the last item in the list, the head should point to the first item's tail in the list. How do I achieve this? Any articles or help would be appreciated
Posted

What you are looking for is a circular linked list.
http://navaneethkn.wordpress.com/2009/08/18/circular-linked-list/[^] is a very good resource and should help you out.
 
Share this answer
 
Try:
C#
lastItem.Next = head;
That gets the reference for the first item in the list (from head) and assigns it as the next item for the last item.
 
Share this answer
 
Comments
Andrew797 8-Jan-12 11:05am    
I see I cant access an item in a linked list by index, for instance linkedlist[5]; Can this circular effect be accomplished with any other collection type like Hashtable, array, list?
OriginalGriff 8-Jan-12 11:17am    
No - they do not expose their Next or Previous pointers (specifically so people won't mess with them and create infinite loops!)
You could access an item in a linked list by index - but you would have to write an extension method to do it (and it would have to traverse the list to get to the index number)
To be honest, I would set up my own LoopList generic and handle all that myself - it isn't difficult and would reduce the confusion for others! :laugh:
Is there any particular reason why you are trying to set up looped lists?
Andrew797 8-Jan-12 11:20am    
I'm still a student, and its holidays now, so I'm working on a little slot machine, with 3 rows and 5 columns (3 rows and 5 reels) and I'm doing this circular list to prevent the same picture from appearing in the same reel
OriginalGriff 8-Jan-12 11:40am    
Right! Then you do need a circular list.

I would create two classes - Slot and Reel - where Reel contains either a hand made circular list or an array of Slots.
Since a slot machine only needs to access the "front" slot (and maybe three or so each side for "preview"), and is told "Rotate x slots" I would probably go with an array and move an index manually - a lot faster and less hassle than stepping through a list - and handle the wrap from the end to the beginning myself. You may prefer to creat eyou own circlular list - it isn;'t difficult just a little clumsy.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900