Doubly linked list

Hi!

Been working on a doubly linked sorted list,kinda new with it..
having trouble writing the code that will switch order of the elements in the list,for example,if the list consist of:

5,4,3,2 , i want the code to change the order of the elements to "growing order"-> 2,3,4,5

sounds pretty easy,i´ve been trying to draw the nodes on the paper,switching next and prev pointers,cant seem to get it right tho:S

Thanks in advance!
this is what i have writen so far:
cant get the 2nd loop quite right..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
					Node*walker=this->first;
					for(int i=0;i<nrOfNodes;i++)
					{
						walker=walker->next;			
					}
					this->first=walker;
					Node*e=this->first;
					for(int i=0;i<nrOfNodes;i++)
					{
						walker=this->first->prev;
						e=walker->prev;
						e=e->prev;
						walker=walker->prev;
						this->first->next=this->first->prev;

					}
closed account (D80DSL3A)
You want to swap the values of prev and next for each Node in the list.
I just wrote this reverse() for my own double linked list, but I keep a pointer to last instead of keeping count of the Nodes. Having a pointer to the last Node is useful so you can iterate through the list from either end.
This function works. Hopefully you can adapt it to your list. In my code head = first.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void list::reverse()
{
	node* w = head;
	while(w)
	{
		// swap values of next and prev pointers
		node* t = w->next;
		w->next = w->prev;
		w->prev = t;
		// iterate to the node which was next
		w = w->prev;
	}
	// swap values of head and tail pointers
	w = head;
	head = tail;
	tail = w;
	return;
}

Couldnt apply your code to my program:<

have wroten this in the 2nd loop instead:

1
2
					walker->next=this->first->prev;
					walker=walker->next;


should work acording to my sketches,but the program crashes:<
closed account (D80DSL3A)
First is first. It has no prev.
ie: first->prev = NULL; so you may be trying to use a NULL pointer there.
Sorry my code was worthless to you.
Topic archived. No new replies allowed.