LeetCode之24----Swap Nodes in Pairs
来源:互联网 发布:最新网络流行歌曲2016 编辑:程序博客网 时间:2024/06/11 13:57
题目:
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.
题目大意:
给定一条链表,将链表相邻的两个节点交换,返回交换后的链表。
思路:
本题比较简单,大致解题方向有两种:交换节点的值、交换节点的指向。
1、交换节点的值:最简单的方法就是交换两个节点的值,达到交换的目的。
2、交换相邻节点的指向,在即当p2 = p1->next时执行p1->next = p2->next,p2->next = p1。但是在交换的过程中还要保证交换后p2的前驱节点是交换前p1的前驱。
3、还是交换节点的思路,只不过这次的考虑方向不是进行循环交换,而是通过递归来交换。递归的这种程序简洁,重点在于思考方式的不同。在这道题里递归的思考方式是考虑一对的情况,然后将这个分析结果应用到后边的节点,递归下去,解出结果。
代码:
换值:
ListNode* swapPairs(ListNode* head) { ListNode *p1 = head, *p2; int tmp; while(p1) { p2 = p1->next; if (p2) { tmp = p1->val; p1->val = p2->val; p2->val = tmp; p1 = p1->next; } p1 = p1->next; } return head; }
换指针:
ListNode* swapPairs(ListNode* head) { ListNode *p1 = head, *p2, *tmp; if (p1 && p1->next) { head = head->next; } tmp = head; while(p1) { p2 = p1->next; if (p2) { p1->next = p2->next; p2->next = p1; if (tmp != head) tmp ->next = p2; tmp = p1; } p1 = p1->next; } return head;}
换指针(递归版):
ListNode* swapPairs(ListNode* head) { ListNode* p1; if(head && head->next){ p1 = head->next; head->next = swapPairs(head->next->next); p1->next = head; head = p1; } return head;}
0 0
- LeetCode之24----Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- LeetCode 之 Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- 【LeetCode】之Swap Nodes in Pairs
- 【Leetcode】之Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- Leetcode 之 Swap Nodes in Pairs
- LeetCode(24)Swap Nodes in Pairs
- [LeetCode 24] Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- LeetCode | #24 Swap Nodes in Pairs
- [Leetcode 24 链表]Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- 惠普HPwin系统装虚拟机无64bits
- OpenCV2应用Meanshift查找相似物体
- 封装一个View做文件夹管理器
- Memcached 使用记录(以及解决数据不同步的问题的方案)
- javascript入门篇之基础语法
- LeetCode之24----Swap Nodes in Pairs
- uvalive4394(区间dp)
- 下面的方法,当输入为2的时候返回值是多少?
- HDU 1501 Zipper
- Java(1)抽象(abstract)类与抽象方法
- MyBatis springboot gradle 开发配置
- Heat Stack 创建过程分析
- Redis数据库安装部署
- Power of Three ,判断一个数是否为3的n次幂