[leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)

(一)迭代法

在处理这种问题时,我们通常加上一个dummy头结点指向head,至于思路很清晰了就是隔一个去交换两个相邻结点,比如1->2->3->4->NULL,,我们先通过指针交换1和2,再交换3和4,详细的指针操作可以看下面的图:

class Solution {public:ListNode* swapPairs(ListNode* head) {ListNode *dummy=new ListNode(0);dummy->next=head;ListNode *prev=dummy,*cur=head;while(cur&&cur->next){prev->next=cur->next;cur->next=cur->next->next; //先确定后继prev->next->next=cur;prev=cur;cur=cur->next;}return dummy->next;}};(二)递归版本

递归一向是以精巧著称,我们只需处理好最基础的一部分,剩下的递归即可。如果读者不是很理解的话,可以手动模拟一下。

class Solution {public:ListNode *swapPairs(ListNode *head) {if (head == NULL)return NULL;if (head -> next == NULL)return head;ListNode *tmp = head -> next;head -> next = swapPairs(tmp -> next);tmp -> next = head; // 指向下一部分return tmp;}};

版权声明:本文为博主原创文章,未经博主允许不得转载。

其实生命无论长短,只要我们能努力绽放出生命的光彩,便会拥有精彩的人生。

[leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)

相关文章:

你感兴趣的文章:

标签云: