[LeetCode] 24. Swap Nodes in Pairs
来源:互联网 发布:sql server 2005 端口 编辑:程序博客网 时间:2024/05/16 07:02
思路:
用三个指针进行操作. 现将两个指针指向当前的节点对, 然后将上一个节点对和当前节点对连接好, 然后交换当前节点对的位置, 最后做一些为下一轮指针处于正常位置的的准备工作. 详细看注释.
ListNode* swapPairs(ListNode* head) { if (! head || ! head->next) return head; ListNode* cur = head; // 当前节点, 一般指向节点对的后一个节点 ListNode* prev1 = NULL; // 前节点, 一般指向节点对的前一个节点 ListNode* prev2 = NULL; // 前前节点, 一般指向上一对节点对的后一个节点 while (cur && cur->next) { // 挪到新的一对节点处 prev1 = cur; cur = cur->next; // 更新头结点 if (prev1 == head) head = cur; // 将上一对的尾节点和当前头结点连在一起 if (prev2) prev2->next = cur; ListNode* pNext = cur->next; // 交换当前这对节点的顺序 cur->next = prev1; prev1->next = pNext; // 前前指针指向当前节点对的尾节点, 为下轮循环连接下一个首节点做准备 prev2 = prev1; // cur挪到下一对的首节点 cur = pNext; } return head;}
0 0
- [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
- 【LeetCode】24.Swap Nodes in Pairs
- [leetcode] 24.Swap Nodes in Pairs
- **LeetCode 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs LeetCode
- 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
- LeetCode-24.Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- 1.在windows下安装Node.js
- 接口中的域
- 51nod 1058 N的阶乘的长度 数学
- 自立·爱
- 面向切面编程(AOP)的理解
- [LeetCode] 24. Swap Nodes in Pairs
- Git常见错误
- 35 第一个只出现一次的字符
- PAT乙级.1012. 数字分类 (20)
- 无向图最小割
- 【Leetcode】 83. Remove Duplicates from Sorted List 【两个指针】
- python的多线程基础设施
- HDU 2448 Mining Station on the Sea(floyd+KM)
- java网络编程