开发者

moving an element down in a list c++

开发者 https://www.devze.com 2023-03-07 16:27 出处:网络
I need some help, I need to be able to fin开发者_运维技巧d an element in a linked list and move it down in the list. How can I do this?

I need some help, I need to be able to fin开发者_运维技巧d 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


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 :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消