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.

题解:

  没什么好写的,链表题一般要注意头结点的问题,还有一定要画图!

Solution 1

 /**
* 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 dummy(-);
dummy.next = head;
ListNode* cur = &dummy; while (cur->next && cur->next->next) {
ListNode* tmp = cur->next->next;
cur->next->next = tmp->next;
tmp->next = cur->next;
cur->next = tmp;
cur = tmp->next;
} return dummy.next;
}
};

  递归:

Solution 2

 /**
* 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* newHead = head->next;
head->next = swapPairs(head->next->next);
newHead->next = head;
return newHead;
}
};

最新文章

  1. Xamarin.Android活动的生命周期
  2. 基于Ruby的watir-webdriver自动化测试方案与实施(二)
  3. 重装Ubuntu16.04及安装theano
  4. BZOJ 2668 交换棋子(费用流)
  5. Apache安全配置方案
  6. C#验证码
  7. Delphi - 闲来无事,自己写个Timer玩玩(多线程Timer)
  8. FZU2181+poj2942(点双连通+判奇圈)
  9. json在线编辑器
  10. poj2485 highwaysC语言编写
  11. Hadoop学习笔记02_MapReduce练习
  12. git不添加.idea等IDE配置文件夹
  13. Window上,启动Tomcat服务之后,关闭启动窗口,服务器也随之关闭
  14. luogu P2486 [SDOI2011]染色
  15. 基于bootstrap的后台左侧导航菜单和点击二级菜单刷新二级页面时候菜单展开显示当前菜单
  16. 【转】Java计算文件的hash值
  17. zabbix 3.2.5 agent端(源码包)安装部署 (二)
  18. Probability Concepts
  19. Sencha中Element的使用
  20. UnsupportedOperationException:can't convert to dimension :typx=0x1

热门文章

  1. c语言的编译和运行流程
  2. Discrete Function(简单数学题)
  3. POJ 1068 Parencodings【水模拟--数括号】
  4. Virtualbox报错------> '/etc/init.d/vboxdrv setup'
  5. spring 事物管理
  6. Android TextView文字过多时通过滚动条显示多余内容
  7. C#读取excel 找不到可安装的ISAM
  8. 禁用chrome浏览器的cookie
  9. oracle游标用法
  10. rest-client restclient get post写法