LeetCode 24. Swap Nodes in Pairs(按对交换单链表结点)
2018-03-18 19:21
513 查看
题目描述:
Given a linked list, swap every two adjacent nodes and return its head.
For example, Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
分析:
题意:给定一个单链表,对于每两个相邻的结点,交换它们的顺序,并返回结果。
思路:这道题考察头插法(之前有说明,头插法逆序,尾插法正序)。为了方便操作,我们用指针h建立一个空结点(方便指针s的操作,同时保存最终结果)。我们用一个flag标记来说明当前结点是每一对结点的开始或者结尾。flag为true时,一对结点已经交换完毕,然后接下去处理另一对结点,此时指针s指向下一对结点的开始位置。
假设单链表包含n个结点,那么时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
// Exceptional Case:
if(!head || !head->next){
return head;
}
ListNode * p = head, *r;
ListNode *h = new ListNode(-1), *s = h;
bool flag = false;
// every two nodes: head insert method
while(p){
r = p;
p = p->next;
r->next = s->next;
s->next = r;
flag = !flag;
if(!flag){
s = s->next->next;
}
}
return h->next;
}
};
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.
分析:
题意:给定一个单链表,对于每两个相邻的结点,交换它们的顺序,并返回结果。
思路:这道题考察头插法(之前有说明,头插法逆序,尾插法正序)。为了方便操作,我们用指针h建立一个空结点(方便指针s的操作,同时保存最终结果)。我们用一个flag标记来说明当前结点是每一对结点的开始或者结尾。flag为true时,一对结点已经交换完毕,然后接下去处理另一对结点,此时指针s指向下一对结点的开始位置。
假设单链表包含n个结点,那么时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
// Exceptional Case:
if(!head || !head->next){
return head;
}
ListNode * p = head, *r;
ListNode *h = new ListNode(-1), *s = h;
bool flag = false;
// every two nodes: head insert method
while(p){
r = p;
p = p->next;
r->next = s->next;
s->next = r;
flag = !flag;
if(!flag){
s = s->next->next;
}
}
return h->next;
}
};
相关文章推荐
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- 【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- [Leetcode] Swap nodes in pairs 成对交换结点
- [LeetCode] 24. Swap Nodes in Pairs 成对交换节点
- (Java) LeetCode 24. Swap Nodes in Pairs —— 两两交换链表中的节点
- LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
- 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)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 解题报告
- leetcode--24. Swap Nodes in Pairs