leetcode解题报告24. Swap Nodes in Pairs
来源:互联网 发布:nginx websocket 转发 编辑:程序博客网 时间:2024/06/03 17:36
leetcode解题报告24. Swap Nodes in Pairs
题目地址
难度是medium
题目描述
给定一个链表,把相邻的元素交换位置
比如
给定1->2->3->4->5
变成2->2->4->3->5
我的思路
题目的核心操作是交换两个相邻元素,如果链表长度是2,则问题就变成简单的交换两个相邻元素。于是可以考虑用递归的方法,每次只处理两个元素。当然用循环遍历的方式逐步处理应该也是可以的,但是这时处理头指针比较麻烦。用递归的方式代码会更简洁
我的代码
递归版本
/** * 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) { return func(head); } ListNode* func(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode *p1, *p2; p1 = head->next; p2 = head->next->next; p1->next = head; head->next = func(p2); return p1; }};
循环版本
/** * 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) { if (head == NULL || head->next == NULL) return head; ListNode *p0, *p1, *p2; p0 = head; p1 = head->next; p2 = head->next->next; head = head->next; ListNode *tail = NULL; while (true) { p1->next = p0; p0->next = p2; if (tail == NULL) { tail = p0; } else { tail->next = p1; tail = p0; } if (p2 == NULL || p2->next == NULL) { return head; } else { p0 = p2; p1 = p2->next; p2 = p2->next->next; } } return head; }};
阅读官方题解
没有官方题解。
思想核心总结
链表的问题要善于画图
阅读全文
0 0
- LeetCode解题报告--Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- Swap Nodes in Pairs LeetCode 解题报告
- 【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 javascript解题]Swap Nodes in Pairs
- Swap Nodes in Pairs ——解题报告
- [LeetCode]24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode Python
- LeetCode --- 24. Swap Nodes in Pairs
- LeetCode 24.Swap Nodes in Pairs
- [Leetcode] 24. Swap Nodes in Pairs
- JSP内置对象request的方法
- Python练习8---字典的运用
- JavaScript若干盲点总结
- FPM(FastCGI Process Manager)
- OSG学习:响应键盘鼠标示例
- leetcode解题报告24. Swap Nodes in Pairs
- 【c++面试题】c++中函数的重载,c++程序中调用C编译器编译后的函数为什么要加extern "C"
- C语言
- POJ 3126 Prime Path(bfs+素数打表)
- 打印流PrintWriter实现自动刷新和换行
- 线程安全与可重入函数
- httpd编译安装第三方模块示例
- Linux搭建—NFS服务的安装与配置
- 读书笔记-人月神话14