- 【leetcode】24. Swap Nodes in Pair
- 24. Swap Nodes in Pairs
- [leetcode] 24 swap nodes in pair
- 24. Swap Nodes in Pairs {Medium}
- LeetCode-24 - Swap Nodes in Pair
- Leetcode【24、109、328、445、725】
- LeetCode 24. Swap Nodes in Pairs
- Leetcode 24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- Leetcode 24. Swap Nodes in Pairs
1、题目描述
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
2、问题描述:
- 成对的交换,不能改动结点的值。
3、问题关键:
4、C++代码:
/**
* 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) {
if (!head || !head->next) return head;
auto p = head;
auto dummy = new ListNode(-1), pre = dummy;
while(p && p->next) {
auto t = p->next->next;
pre->next = p->next;
p->next->next = p;
p->next = t;
pre = p, p = t;
}
return dummy->next;
}
};
网友评论