leetcode解题之24. Swap Nodes in Pairs java 版(成对翻转链表)
来源:互联网 发布:淘宝真空压缩袋 编辑:程序博客网 时间:2024/05/16 10:30
24. Swap Nodes in Pairs
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 maynot modify the values in the list, only nodes itself can be change
成对交换链表
自己的笨方法,AC,准备两个list,一个存放第奇数个结点,一个存放偶数个结点,取的时候反过来。合成一个,最后就是结果,注意最后需要把尾结点置空
public ListNode swapPairs(ListNode head) {if (head == null)return null;List<ListNode> first = new ArrayList<>();List<ListNode> second = new ArrayList<>();ListNode cur = head;ListNode ph = new ListNode(0);int i = 0;while (cur != null) {if ((i & 1) == 0)first.add(cur);elsesecond.add(cur);cur = cur.next;i++;}cur = ph;while (!first.isEmpty() && !second.isEmpty()) {cur.next = second.get(0);cur = cur.next;cur.next = first.get(0);cur = cur.next;first.remove(0);second.remove(0);}if (!second.isEmpty()) {cur.next = second.get(0);cur = cur.next;}if (!first.isEmpty()) {cur.next = first.get(0);cur = cur.next;}cur.next = null;return ph.next;}参考代码:
public ListNode swapPairs(ListNode head) {if (head == null || head.next == null)return head;// 防止丢链ListNode tmpHead = new ListNode(0);// ptr1始终指向需要交换的pair的前面一个node,ListNode ptr1 = tmpHead;// ptr2始终指向需要交换的pair的第一个node。ListNode ptr2 = head;// 当链表长度为奇数时,ptr2.next可能为null;// 当链表长度为偶数时,ptr2可能为null。while (ptr2 != null && ptr2.next != null) {// 需要用一个临时指针nextstart, 指向下一个,// 需要交换的pair的第一个node保证下一次交换的正确进行。ListNode nextstart = ptr2.next.next;ptr2.next.next = ptr2;ptr1.next = ptr2.next;ptr2.next = nextstart;ptr1 = ptr2;ptr2 = nextstart;}return tmpHead.next;}
0 0
- leetcode解题之24. Swap Nodes in Pairs java 版(成对翻转链表)
- [leetcode 24]Swap Nodes in Pairs-----成对翻转链表中的节点
- 【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素
- [LeetCode]Swap Nodes in Pairs 成对交换
- LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)
- 24. Swap Nodes in Pairs -leetcode-java
- (Java)LeetCode-24. Swap Nodes in Pairs
- [LeetCode-Java]24. Swap Nodes in Pairs
- [leetcode]24. Swap Nodes in Pairs(java)
- [LeetCode] 24. Swap Nodes in Pairs java
- 【Java】LeetCode进阶之路(Swap Nodes in Pairs)
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- Leetcode #24. Swap Nodes in Pairs 链表节点交换 解题报告
- LeetCode解题报告--Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- [leetcode javascript解题]Swap Nodes in Pairs
- Swap Nodes in Pairs LeetCode 解题报告
- url match
- The request sent by the client was syntactically incorrect 服务器,tomcat,网页请求错误400,
- poj 2406 Power Strings
- 签到
- 进程与优先级,ps命令,前后台的调用,用户登录审计,top
- leetcode解题之24. Swap Nodes in Pairs java 版(成对翻转链表)
- Javascript获取select下拉框选中的的值
- 十年Java开发经验人员精心总结编制的Java学习脑图
- poj 2155 Matrix(二维树状数组)
- Redis简介(二)
- CSS入门笔记
- jeecg下拉框功能的实现
- Java内存模型
- 第五届蓝桥杯B组Java—地宫取宝