LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
来源:互联网 发布:晨曦软件视频教程 编辑:程序博客网 时间:2024/05/21 22:52
- 题目
- 题意
- 注意
- 思路
- 代码
- 结果
- 题目
题目
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.
题意
给定一个链表,交换相邻的两个结点,返回交换之后的头结点
注意
是交换相邻的元素,也是说,两两交换,交换之后不在参与,当不满足两个元素不用交换
思路
设置四个指针,pre,node1,node2,next。关键在于pre指针。
代码
class Solution {public: ListNode* swapPairs(ListNode* head) { ListNode *virtualNode = new ListNode(0); virtualNode->next = head; ListNode *pre = virtualNode; while(pre->next!=NULL&&pre->next->next != NULL) { ListNode* node1 = pre->next; ListNode* node2 = node1->next; ListNode* next = node2->next; node2->next = node1; node1->next = next; pre->next = node2; pre = node1; } ListNode* resNode = virtualNode->next; delete virtualNode; return resNode; }};
结果
阅读全文
0 0
- LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
- [LeetCode]Swap Nodes in Pairs 交换节点
- LeetCode 24. Swap Nodes in Pairs(交换节点)
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- [LeetCode] Swap Nodes in Pairs(成对交换节点)
- 24. Swap Nodes in Pairs-节点交换|指针
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- Leetcode #24. Swap Nodes in Pairs 链表节点交换 解题报告
- [LeetCode]Swap Nodes in Pairs 成对交换
- LeetCode-------24. Swap Nodes in Pairs(两两交换)
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- [C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)
- Leetcode Swap Nodes in Pairs 交换链表的节点对
- 【链表&交换邻节点】Swap Nodes in Pairs
- Swap Nodes in Pairs 链表交换相邻的节点
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- Swap Nodes in Pairs 交换LinkList的相邻节点
- 用阿里云搭建web服务器
- sdkman工具的使用
- InnoDB_MyISAM
- php curl 获取数据不完整
- 【源码分析】Guava源码解析之EventBus
- LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
- Vh和Vw的简介和使用
- JavaScript RegExp
- MyBatis(三) xml文件解析流程 动态SQL解析
- 音视频:AVAudioPlayer:中断处理
- 算法作业19
- 另类的电脑弹窗,无法查杀,也找不出!
- ARC和MRC下的block的内存分布详解
- Hibernate一对一关联映射(注解)