LeetCode - 24. Swap Nodes in Pairs
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - 24. Swap Nodes in Pairs相关的知识,希望对你有一定的参考价值。
24. Swap Nodes in Pairs
Problem‘s Link
----------------------------------------------------------------------------
Mean:
给定一个链表,交换这个链表两两相邻的元素.
analyse:
略
Time complexity: O(N)
view code
/**
* -----------------------------------------------------------------
* Copyright (c) 2016 crazyacking.All rights reserved.
* -----------------------------------------------------------------
* Author: crazyacking
* Date : 2016-02-19-10.35
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long(LL);
typedef unsigned long long(ULL);
const double eps(1e-8);
// 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==nullptr)
return head;
ListNode *frontPtr=head,*backPtr=head->next;
while(frontPtr && backPtr)
{
swap(frontPtr->val,backPtr->val);
frontPtr=frontPtr->next;
if(frontPtr!=nullptr)
frontPtr=frontPtr->next;
backPtr=backPtr->next;
if(backPtr!=nullptr)
backPtr=backPtr->next;
}
return head;
}
};
int main()
{
return 0;
}
/*
*/
* -----------------------------------------------------------------
* Copyright (c) 2016 crazyacking.All rights reserved.
* -----------------------------------------------------------------
* Author: crazyacking
* Date : 2016-02-19-10.35
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long(LL);
typedef unsigned long long(ULL);
const double eps(1e-8);
// 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==nullptr)
return head;
ListNode *frontPtr=head,*backPtr=head->next;
while(frontPtr && backPtr)
{
swap(frontPtr->val,backPtr->val);
frontPtr=frontPtr->next;
if(frontPtr!=nullptr)
frontPtr=frontPtr->next;
backPtr=backPtr->next;
if(backPtr!=nullptr)
backPtr=backPtr->next;
}
return head;
}
};
int main()
{
return 0;
}
/*
*/
以上是关于LeetCode - 24. Swap Nodes in Pairs的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode-24 Swap Nodes in Pairs
LeetCode 24 Swap Nodes in Pairs
Leetcode24. Swap Nodes in Pairs
Leetcode24. Swap Nodes in Pairs