I am trying to make a circular linked list.
I will appreciate if anyone can tell me how to make it better.

int n = num_people;
		Node *head = new Node;
		head->next = new Node;		
		Node *temp = head->next;
		for(int x = 2; x < n; x++)
		{
			temp->next = new Node;
			temp = temp->next;		
			if(x == (n - 1))
			{
				temp = NULL;
			}
		}
		if(temp == NULL)
		{
			temp = head;
		}

Thank you.

Edited 6 Years Ago by Nick Evan: added code-tags

Unfortunately I don't have answer to your question, but I have two suggestions
1) make a much more descriptive title - this will entice people to investigate your problem
2) Please use code tags. This makes the code that you post much more readable.

Dave

>> How can I edit my post, should I post it again with a different title.

No don't. I've changed it for you.

Where's the rest of the code?

why don't you take another approach to solve this problem. I would suggest using a pointer called " start " to mark the beginning of the list and then use another pointer called "p" to enlarge the list. The pointer "p" will be changed as needed. give it a shot and i'm ready for help.

try to make your could neat :)

Thanks for helping me out.
Is this what you meant:

int n = num_people;
		Node *start = new Node;
		start->next = new Node;	
		Node *p = start->next;
		for(int x = 2; x < n; x++)
		{
			p->next = new Node;
			p = p->next;		
			if(x == (n - 1))
			{
				p = NULL;
			}
		}
		if(p == NULL)
		{
			p = head;
		}

Edited 6 Years Ago by achieve_goals: n/a

Actually u got quit of what i meant. Good, but its possible to make the code simpler. you can do it this way:

for ( int c = 1; c<=n; c++ )// making the circular list.   
	{
		if (c==n)
		{
			p->next = start;
		}
		else
		{
			p -> next = new node;
			p=p->next;
		}
	}
	p=start;

Note that there is no need to use ( head & start ) pointers twice, one of them is enough. Also the (n-1) way made it confusing and a little bit complicated. Always to try to make your code simple and stupid. i hate to give the answer directly with out making you to figure it out your self, but its my fault i replied late and i think its not worth waiting this long time if we gonna make it step by step.

This question has already been answered. Start a new discussion instead.