#451 Swap Nodes in Pairs
2016-08-12 11:48
295 查看
题目描述:
Given a linked list, swap every two adjacent nodes and return its head.
Have you met this question in a real interview?
Yes
Example
Given
should return the list as
Challenge
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
题目思路:
这题继续用好用的dummy head,然后就是指针swap,需要注意的是swap过程中的顺序。
Mycode(AC = 31ms):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @return a ListNode
*/
ListNode* swapPairs(ListNode* head) {
// Write your code here
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *tmp = dummy, *next = dummy->next;
while (next && next->next) {
tmp->next = next->next;
next->next = tmp->next->next;
tmp->next->next = next;
tmp = next;
next = tmp->next;
}
return dummy->next;
}
};
Given a linked list, swap every two adjacent nodes and return its head.
Have you met this question in a real interview?
Yes
Example
Given
1->2->3->4, you
should return the list as
2->1->4->3.
Challenge
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
题目思路:
这题继续用好用的dummy head,然后就是指针swap,需要注意的是swap过程中的顺序。
Mycode(AC = 31ms):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @return a ListNode
*/
ListNode* swapPairs(ListNode* head) {
// Write your code here
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *tmp = dummy, *next = dummy->next;
while (next && next->next) {
tmp->next = next->next;
next->next = tmp->next->next;
tmp->next->next = next;
tmp = next;
next = tmp->next;
}
return dummy->next;
}
};
相关文章推荐
- lintcode-Swap Nodes in Pairs -451
- leetcode 14: Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs(成对交换节点)
- Swap Nodes in Pairs
- [leetcode] Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- LeetCode——Swap Nodes in Pairs
- Letter Combinations of a Phone Number,Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- Swap Nodes in Pairs--LeetCode
- 24. Swap Nodes in Pairs (java实现)
- LeetCode *** 24. Swap Nodes in Pairs
- Swap Nodes in Pairs
- Leetcode 24 :Swap Nodes in Pairs
- Leetcode 24. Swap Nodes in Pairs 分治
- [Leetcode]Swap Nodes in Pairs
- Swap Nodes in Pairs
- 【LeetCode练习题】Swap Nodes in Pairs
- leetcode 132: Swap Nodes in Pairs