leetcode 24 Swap Nodes in Pairs
来源:互联网 发布:手机rmvb视频剪辑软件 编辑:程序博客网 时间:2024/06/05 00:27
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 as2->1->4->3
.
Your algorithm should use only constant space. You maynot modify the values in the list, only nodes itself can be changed.
这道题是对链表的简单处理,代码如下:
/**
* 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)
{
ListNode *p,*q,*f,*temp;
if(head!=NULL&&head->next!=NULL)
{
p=head;
q=head->next;
temp=q->next;
head=q;
q->next=p;
p->next=temp;
f=head->next;
}
else
{
return head;
}
while(f->next!=NULL&&f->next->next!=NULL)
{
p=f->next;
q=f->next->next;
temp=q->next;
f->next=q;
q->next=p;
p->next=temp;
f=p;
}
return head;
}
};
需要注意的是,在这道题中没有头节点,head所指向的节点为第一个节点而不是头节点。
- LeetCode(24)Swap Nodes in Pairs
- [LeetCode 24] Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- LeetCode | #24 Swap Nodes in Pairs
- [Leetcode 24 链表]Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- Leetcode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode 24 - Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode-24Swap Nodes in Pairs
- leetcode 24: Swap Nodes in Pairs
- Leetcode#24 Swap Nodes in Pairs
- LeetCode 24: Swap Nodes in Pairs
- LeetCode(24) Swap Nodes in Pairs
- [Leetcode 24, Medium] Swap Nodes in Pairs
- 回溯法
- ofbiz的webservice接口提供(3)-不规范的wsdl的客户端访问代码
- 初级ViewPager
- 使用163yum源
- php常用表单验证类
- leetcode 24 Swap Nodes in Pairs
- Python--psutil
- Too many open files
- Linux下PHP加速器APC的安装与配置
- 欢迎使用CSDN-markdown编辑器(CSDN自动提供)
- 数据结构实验之查找三:树的种类统计
- 为何专利总是抓不到对手侵权?-Capability Claim对直接侵权的影响
- VS2010/MFC编程入门之三(VS2010应用程序工程中文件的组成结构)
- yii2数据库查询操作