adsderek
adsderek

Reputation: 23

moving an element down in a list c++

I need some help, I need to be able to find an element in a linked list and move it down in the list. How can I do this?

example: 1 2 3 4

find 2 and switch with next

output: 1 3 2 4

move 2 two spaces down 2 3 4 1

Upvotes: 1

Views: 4048

Answers (1)

Jason
Jason

Reputation: 32520

If you're using std::list, this is fairly simple. First, do a search for your number, getting you an iterator to that position in the list. For example:

std::list<int> mylist;

//populate your list with the digits you want

//find the element in the list
int element = 5;
std::list<int>::iterator current = mylist.begin();
for (; current != mylist.end(); current++)
{
    if (*current == element)
        break;
}

//Now move your element two positions back (let's assume you have the elements in
//the list to-do that amount of movement, but nevertheless,
//we still check the list bounds and exit the loop if we hit the front of the list)
for (std::list<int>::iterator new_position = current, int i=0; 
     (i < 2 && new_position != mylist.begin()); 
     i++, new_position--);

mylist.insert(new_position, 1, *current);

//erase where the element used to be
mylist.erase(current);

And if you're not using std::list, use std::list :-)

Upvotes: 1

Related Questions