Redian新闻
>
怎么理解递归解决的“swap every two elements in a linked list”?
avatar
怎么理解递归解决的“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;
}
avatar
p*p
2
swap退栈的时候返回一组两个中的第二个,例如
1-2-3-4
1-2一组,3-4一组
a. swap(1)的时候执行到那行把2的next指向下个swap返回上来的node
b. 然后swap(3)被调用,返回node4,退栈
c. 4返回的时候又到a那步,2的next就拿到了4
然后继续走下去so on so forth
avatar
B*t
3
ListNode *swapPairs(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL || head->next == NULL)
return head;
else
{
ListNode *temp = head->next;
head->next = swapPairs(head->next->next);
temp->next = head;
return temp;
}
}

->

【在 n*****g 的大作中提到】
: 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;

avatar
c*t
4
我不理解的是 那句 first=second;
需要吗?

->

【在 n*****g 的大作中提到】
: 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;

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。