2014-06-28 60 views
0

问题:给定一个带有三个指针的链表:第一个指向第一个节点,第二个指向第三个,第三个指向最后一个节点。将单个指针返回到同一个列表,以便第五个是第一个,第一个是最后一个。在链表中移动指针

这是在课堂上给我们的一个问题,我很难理解这个问题,但这里是我的尝试解决方案。

//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的解决方案

+0

_'I我会进一步赞赏一个解决方案,利用STL'_这将简单地使用['std :: list'](http://en.cppreference.com/w/cpp/container/list) –

+0

这就是正确,但我不知道如何使用std :: list来完成此操作 – user3786689

+0

@ user3786689您是否必须使用原始指针,或者我们只需引用列表并使用其内置函数呢? – IllusiveBrian

回答

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。现在你必须做的最后一件事是让第一名成为第五名。为此,你需要把它指向第二个。就是这样。据我了解,你应该把它包含在一个函数中,然后返回。

+0

你真了不起!谢谢 :) – user3786689