的解决方案
问题:给定一个有三个指针的链表:第一个指向第一个节点,第二个指向第三个节点,第三个指向最后一个节点。返回指向同一列表的单个指针,使第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
可以这样做:
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号。你需要让它指向2。就是这样。据我所知,您应该将其包装在一个函数中,该函数首先返回