好贷网好贷款

LeetCode | Swap Nodes in Pairs

发布时间:2016-12-3 3:50:51 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"LeetCode | Swap Nodes in Pairs",主要涉及到LeetCode | Swap Nodes in Pairs方面的内容,对于LeetCode | Swap Nodes in Pairs感兴趣的同学可以参考一下。

题目: Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 思路: 链表依次交换,道理很简单,关键是细心。 代码: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function ListNode* p = head; ListNode* begin = NULL; if(p == NULL) { return NULL; } if(p->next != NULL) { ListNode* t = p; p = p->next; t->next = p->next; p->next = t; if(begin == NULL) { begin = p; } p = p->next; } else { return head; } if(p == NULL) { return begin; } while(p->next != NULL) { if(p->next->next != NULL) { ListNode* t = p->next->next; p->next->next = t->next; t->next = p->next; p->next = t; p = p->next->next; } else { break; } if(p == NULL) { break; } } return begin; } }; 仔细观察如上的代码,我们会发现其实我们可以用一个递归的方式来简单实现该代码。 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { ListNode* p = head; ListNode* begin = NULL; if(p == NULL) { return NULL; } if(p->next != NULL) { ListNode* t = p; p = p->next; t->next = p->next; p->next = t; if(begin == NULL) { begin = p; } p = p->next; } else { return head; } p->next = swapPairs(p->next); return begin; } };

上一篇:Visual Basic COM基础讲座之
下一篇:DTD学习

相关文章

相关评论