题目

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;
}
};

最新文章

  1. WEB前端工程师面试题【前端】
  2. get/post方式调用http接口
  3. android:windowSoftInputMode及其他部分属性用法
  4. opsview
  5. 如何成为apple开发者???
  6. 批量修改文件后缀(Python)
  7. namenode无法启动(namenode格式化失败)
  8. ajax_for example
  9. MBR
  10. ./scripts/feeds update -a OpenWrt大招系列
  11. PHP学习笔记12-上传文件
  12. linux下安装oracle11g 64位最简客户端(转)
  13. C#格式符
  14. Java数据持久层框架 MyBatis之API学习五(Mapper XML 文件)
  15. C作业--初步
  16. js 对象,数组,字符串,相互转换
  17. J2EE [web] 403.500.404页面配置
  18. python多线程相关知识点
  19. TensorFlow学习笔记(8)--网络模型的保存和读取【转】
  20. Java之IO(五)文件系统

热门文章

  1. System Center Configuration Manager 2016 必要条件准备篇(Part1)
  2. 根据accept-language自动设置UICulture和Culture
  3. centos升级3.10内核到4.4
  4. centos开机启动自定义脚本
  5. iOS 集成支付宝过程中 我遇到的一些坑,请大家注意啦(ALI69错误,ALI64错误)
  6. matlab中size函数总结
  7. java 实现猜数字游戏 随机给定一个数字,猜大小直到正确
  8. mysql主从复制及双主复制
  9. 问题:Could not install packages due to an EnvironmentError: [Errno 13] Permission denied:
  10. JZOJ 5347. 遥远的金字塔