[分析:用双指针来实现,两指针间隔m。同步移动两指针,当前一个指针为该链表tail时,后一个指针就为要找的元素]
Element * FindMToLastElement( Element * head, int m)
{
Element * current, * mBehind;
int i;
for( i = 0; i < m; i++)
{
if(current->next)
{
current = current->next;
}
else
{
return NULL;
}
}
mBehind = head;
while(current->next)
{
current = current->next;
mBehind = mBehind->next;
}
return mBehind;
}
typedef struct Node{
struct Node * next;
struct Node * prev;
struct Node * child;
int value;
}Node;
[分析:从第一层链表头开始遍历链表,如果有第二层链表,则将其放到第一层链表尾。这样其实第一层链表尾一直在往后移动,原来的第一层在遍历完后就可以直接遍历第二层了,依此类推就可以完成题目要求,前提要有一个指向尾指针的指针]
void FlattenList( Node * head, Node ** tail)
{
Node * curNode = head;
while( curNode )
{
if(curNode->child)
{
Append(curNode->child, tail);
}
curNode = curNode->next;
}
}
{
Node * curNode;
(*tail)->next = child;
child-prev = *tail;
for(curNode = child; curNode->next; curNode = curNode->next)
{
}
*tail = curNode;
}
[分析:用双指针实现,一个用step=1前进,一个用step=2前进。看两个指针是否能相遇]
bool DetermineTermination( Node * head)
{
Node * fast, * slow;
fast = slow = head;
while(true)
{
if(!fast || !fast->next)
{
return false;
}
else if(fast == slow || fast->next == slow)
{
return true;
}
else
{
slow = slow->next;
fast = fast->next->next;
}
}
}