简体   繁体   中英

Moving around pointers in a linked list

Question: Given a linked list with three pointers: first points to the first node, second to the third and third to the last node. Return a single pointer to the same list so that the 5th is the first and the the first is the last.

This was a question given to us in class, i'm having trouble understanding the question, but here is my attempted solution.

//List is the first pointer
//p is the second pointer (pointing to the third node)
//q is the last pointer (pointing to the last node)

 R = p -> next //R, a name to a pointer i gave that is between p and q
 p -> next = R -> next // don't even know what this means but wrote it down anyways

after this I am stuck, any help is appreciated but I would appreciate the full solution.

I would further appreciate a solution that utilizes STL

It can be done like this:

list *tmp, *tmp2, *pf, p3, pl;    //pf: first, p3: 3rd, pl: last;

tmp = p3->next->next;    //pointer of the 4th element to the 5th;
p3->next->next = tmp->next;    //4th element now pointing to the 6th (since 5th moves to the beggining);
pl->next = pf;    //make the first the last;
tmp2 = pf->next;    //save the pointer to the 2nd;
pf->next = NULL;    //pf is now last (-> pf->next has to be NULL);
tmp->next = tmp2;    //old 5th now pointing to the 2nd (as it should be the first);
pf = tmp;    //make the 5th the first -> this is what you want to return;

What is basically done here: You take out the 5th element (its pointer) out and therefore you have to connect 4 with 6. Now you put the first at the end. This is pretty easy since last->next is NULL anyway. The last thing you have to do now is making the 5th the 1st. For that you need to make it point to the 2nd. And that's it. As far as I understood you should wrap this also in a function which returns first then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM