[LeetCode]24. Swap Nodes in Pairs
2017-05-20 21:10
295 查看
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.
在处理这种问题时,我们通常加上一个h1头结点指向head,至于思路很清晰了就是隔一个去交换两个相邻结点,比如1->2->3->4->NULL,我们先通过指针交换1和2,再交换3和4,具体的操作流程如下:
曲线上的数字代表每次循环的步骤。
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
在处理这种问题时,我们通常加上一个h1头结点指向head,至于思路很清晰了就是隔一个去交换两个相邻结点,比如1->2->3->4->NULL,我们先通过指针交换1和2,再交换3和4,具体的操作流程如下:
曲线上的数字代表每次循环的步骤。
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode *h1 = new ListNode(0); h1->next = head; ListNode *prev = h1, *cur = head; while (cur&&cur->next) { prev->next = cur->next; cur->next = cur->next->next; //确定后继新交换的起点,下面有cur=cur->next prev->next->next = cur; prev = cur; cur = cur->next; //当前为新交换的起始点 } return h1->next; } };
相关文章推荐
- 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 C++
- **LeetCode 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- <LeetCode OJ> 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- 24.[Leetcode]Swap Nodes in Pairs
- Leetcode ☞ 24. Swap Nodes in Pairs ☆
- leetcode 24. Swap Nodes in Pairs(链表)
- LeetCode *** 24. Swap Nodes in Pairs
- (Java)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 (Easy) (cpp)
- [leetcode] 【链表】24. Swap Nodes in Pairs