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