[LeetCode]24. Swap Nodes in Pairs
来源:互联网 发布:软件 先进性 编辑:程序博客网 时间:2024/06/11 00:30
24. 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) { ListNode* dummyHead = new ListNode(0); // 指向dummyHead的指针 ListNode* d_pCur = dummyHead; dummyHead->next = head; ListNode* pCur = head; // 至少两个非空结点才swap while (pCur && pCur->next) { ListNode* temp = pCur->next; ListNode* pNext = pCur->next; pCur->next = pCur->next->next; pNext->next = pCur; d_pCur->next = temp; d_pCur = d_pCur->next->next; pCur = pCur->next; } return dummyHead->next; }};
阅读全文
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
- 抽奖的小程序
- 【第6章】对象和类
- Multiple Threads in the User Interface
- 字符串移动进阶
- [Leetcode] 356. Line Reflection 解题报告
- [LeetCode]24. Swap Nodes in Pairs
- float数据在内存中是如何存储的
- 【dp】POJ
- 芝诺悖论2 阿基里斯与乌龟
- 关于redis统一session的问题
- POJ
- FLV文件格式分析(附源码)
- 百度之星度度熊的交易计划
- 简易推箱子游戏