怎么理解递归解决的“swap every two elements in a linked list”?# JobHunting - 待字闺中
n*g
1 楼
recursive的题我基本没怎么练过,基本只会BST中简单的查找之类的。我做得是网络方
面,感觉面试时候不太需要用到recursive。不过今天看到一面试题还是想弄明白其中
的recursive。想请教各位怎么理解?题目和解决方案如下:
Given a singly linked list, swap every two elements (e.g. a->b->c->d->e->f->
null should become b->a->d->c->f->e->null). Code it such that memory
position is swapped and not the node value.
linknode* swap (linknode* root)
{
if (root==NULL || root->next==NULL)
return root;
linknode* first, *second;
first = root;
if(first && first->next)
{
second = root->next;
first->next= swap(second->next);//这里不太理解啊!!!!!!
second->next=first;
first=second;
}
return second;
}
面,感觉面试时候不太需要用到recursive。不过今天看到一面试题还是想弄明白其中
的recursive。想请教各位怎么理解?题目和解决方案如下:
Given a singly linked list, swap every two elements (e.g. a->b->c->d->e->f->
null should become b->a->d->c->f->e->null). Code it such that memory
position is swapped and not the node value.
linknode* swap (linknode* root)
{
if (root==NULL || root->next==NULL)
return root;
linknode* first, *second;
first = root;
if(first && first->next)
{
second = root->next;
first->next= swap(second->next);//这里不太理解啊!!!!!!
second->next=first;
first=second;
}
return second;
}