【Swap Nodes in Pairs】cpp
2024-08-29 20:44:38
题目:
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.
代码:
/**
* 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;
ListNode dummy(-);
dummy.next = head;
ListNode *prev = &dummy;
ListNode *curr = head;
while ( curr && curr->next )
{
prev->next = curr->next;
curr->next = curr->next->next;
prev->next->next = curr;
prev = curr;
curr = curr->next;
}
return dummy.next;
}
};
Tips:
链表基本操作,动手画图,直接出来。
===================================
第二次过这道题,一次AC了。
/**
* 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 dummpy(-);
dummpy.next = head;
ListNode* pre = &dummpy;
ListNode* curr = head;
while ( curr && curr->next )
{
pre->next = curr->next;
curr->next = curr->next->next;
pre->next->next = curr;
pre = curr;
curr = curr->next;
}
return dummpy.next;
}
};
最新文章
- WEB前端工程师面试题【前端】
- get/post方式调用http接口
- android:windowSoftInputMode及其他部分属性用法
- opsview
- 如何成为apple开发者???
- 批量修改文件后缀(Python)
- namenode无法启动(namenode格式化失败)
- ajax_for example
- MBR
- ./scripts/feeds update -a OpenWrt大招系列
- PHP学习笔记12-上传文件
- linux下安装oracle11g 64位最简客户端(转)
- C#格式符
- Java数据持久层框架 MyBatis之API学习五(Mapper XML 文件)
- C作业--初步
- js 对象,数组,字符串,相互转换
- J2EE [web] 403.500.404页面配置
- python多线程相关知识点
- TensorFlow学习笔记(8)--网络模型的保存和读取【转】
- Java之IO(五)文件系统
热门文章
- System Center Configuration Manager 2016 必要条件准备篇(Part1)
- 根据accept-language自动设置UICulture和Culture
- centos升级3.10内核到4.4
- centos开机启动自定义脚本
- iOS 集成支付宝过程中 我遇到的一些坑,请大家注意啦(ALI69错误,ALI64错误)
- matlab中size函数总结
- java 实现猜数字游戏 随机给定一个数字,猜大小直到正确
- mysql主从复制及双主复制
- 问题:Could not install packages due to an EnvironmentError: [Errno 13] Permission denied:
- JZOJ 5347. 遥远的金字塔