[LeetCode] 115: Swap Nodes in Pairs
来源:互联网 发布:mac图片文件夹在哪里 编辑:程序博客网 时间:2024/06/05 11:17
[Problem]
[Solution]
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.
[Solution]
/**说明:版权所有,转载请注明出处。Coder007的博客
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// short than two nodes
if(NULL == head || NULL == head->next)return head;
// variables definition
ListNode *p1 = head;// the first node
ListNode *p2 = head->next;// the second node
ListNode *pre = p1;// the node before p1
ListNode *after = p2->next;// the node after p2;
// swap
while(p2 != NULL){
// the first pair
if(pre == p1){
head = p2;
}
else{
pre->next = p2;
}
p2->next = p1;
p1->next = after;
// update p1, p2, pre, after
pre = p1;
p1 = pre->next;
if(p1 == NULL)break;
p2 = p1->next;
if(p2 == NULL)break;
after = p2->next;
}
return head;
}
};
阅读全文
0 0
- [LeetCode] 115: Swap Nodes in Pairs
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- 【leetcode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- 【LeetCode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- Leetcode Swap Nodes in Pairs
- [LeetCode] 111: Substring with Concatenation of All Words
- 汇编语言学习(一)
- [LeetCode] 112: Sudoku Solver
- [LeetCode] 113: Sum Root to Leaf Numbers
- [LeetCode] 114: Surrounded Regions
- [LeetCode] 115: Swap Nodes in Pairs
- [LeetCode] 116: Symmetric Tree
- 面试题46. 求1+2+...+n
- [LeetCode] 117: Text Justification
- [LeetCode] 118: Trapping Rain Water
- FYN OI奋斗之路5~
- [LeetCode] 119: Triangle
- [LeetCode] 120: Two Sum
- [LeetCode] 121: Unique Binary Search Trees