leetcode#24 Swap Nodes in Pairs
Posted 老鼠阿尔吉侬
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode#24 Swap Nodes in Pairs相关的知识,希望对你有一定的参考价值。
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
/**
* 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) {
//如果首节点之前有一个结点h,那就好了,我们交换第1、2个结点,再前进2次,交换3、4个结点
//我们可以创造这个结点,也可以先交换1,2结点,让这个结点指向新的第2个结点。这里我用的是第2种办法
if(!head||!head->next) return head;//保证有两个结点
auto h=head;
auto temp=h->next->next;
head=h->next;
h->next->next=h;
h->next=temp;
//现在head:2.。。。21345//h指向1,现在我们可以交换1的后面两个,然后执行循环
while(h->next&&h->next->next)//后2个结点存在
{
auto temp=h->next->next->next;//3
auto t=h->next->next;
h->next->next->next=h->next;
h->next->next=temp;
h->next=t;
h=h->next->next;
}
return head;
}
};
以上是关于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