移动链表中的指针

时间:2014-06-28 21:04:44

标签: c++ data-structures linked-list

问题:给定一个包含三个指针的链表:第一个指向第一个节点,第二个指向第三个节点,第三个指向最后一个节点。返回指向同一列表的单个指针,以便第5个是第一个,第一个是最后一个。

这是我们在课堂上提出的一个问题,我无法理解这个问题,但这是我尝试过的解决方案。

//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

在此之后我被困住了,感谢任何帮助,但我会很感激完整的解决方案。

我将进一步了解利用STL的解决方案

1 个答案:

答案 0 :(得分:0)

可以这样做:

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;

这里基本上做了什么:你取出第5个元素(它的指针),因此你必须连接4和6.现在你把第一个放在最后。这很简单,因为last-> next无论如何都是NULL。你现在要做的最后一件事是将第5名作为第1名。为此你需要指向第二个。就是这样。据我所知,你应该将它包装在一个先返回的函数中。