leetcode 24. Swap Nodes in Pairs
来源:互联网 发布:js 2的指数 编辑:程序博客网 时间:2024/06/02 03:17
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.
这道题考察的是两个节点的交换,这里是指的是指针的交换,而不是值的交换,注意指针即可。
需要注意的地方是:设置head头结点,原因是要对第一队的交换做特殊处理,所以才添加一个head头节点。
代码如下:
/* class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }*//* * 设置head结点,两两交换 * * 设置head的原因是:考虑到第一对结点的交换, * 所以设置head结点,一遍统一处理 * * */public class Solution { public ListNode swapPairs(ListNode head) { if(head==null || head.next==null) return head; ListNode headListNode=new ListNode(-1); headListNode.next=head; ListNode fa=headListNode,now=fa.next,nextNow=now.next; while(now!=null && nextNow!=null) { now.next=nextNow.next; nextNow.next=now; fa.next=nextNow; fa=now; now=fa.next; nextNow=now!=null? now.next : null; } return headListNode.next; }}
下面是C++代码,就是指针交换即可,
代码如下:
#include <iostream>using namespace std;/*struct ListNode{int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};*/class Solution{public: ListNode* swapPairs(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* newHead = new ListNode(-1); newHead->next = head; ListNode* fa = newHead; ListNode* now = fa->next; ListNode* next = now->next; while (now != NULL && next != NULL) { ListNode* tmp = next->next; next->next = now; fa->next = next; now->next = tmp; fa = now; now = fa->next; next = now == NULL ? NULL : now->next; } return newHead->next; }};
阅读全文
0 0
- [LeetCode]24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode Python
- 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
- 24. Swap Nodes in Pairs LeetCode
- 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
- LeetCode 24. Swap Nodes in Pairs
- jenkins学习初步整理
- tomcat+nginx+redis实现均衡负载、session共享(一)
- 信号基本操作之sigprocmask阻塞进程
- Python 图片转存
- 超级表格新功能:表格数据支持卡片模式查看
- leetcode 24. Swap Nodes in Pairs
- 33期C++培训第一天
- CSS实现单行、多行文本溢出显示省略号(…)
- springboot ajax 提交403错误
- 浅谈数据库设计技巧
- maven 解决依赖冲突 omiit for conflict
- Nginx配置多个基于域名的虚拟主机+实验环境搭建+测试
- mysql 数据类型 date 和 datetime 注意
- 3年的程序员之路贵在坚持