Swap Nodes in Pairs 交换LinkList的相邻节点
来源:互联网 发布:mac突然无法连接wifi 编辑:程序博客网 时间:2024/05/18 00:07
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.
解决link list类的问题可以分为两步。
第一步,找出第一阶段的指针该怎么变换。
第二步,找出怎么移动指针到下一阶段。
先来看第一步。
我是利用3个指针来控制,cur指向偶数位的节点(这里是2),pre指向cur的前面一个节点(1),prepre 指向 pre的前面一个节点(一开始让prepre指向伪造的头节点fakeNode)。
如何实现交换?让2指向1,1指向3-> 4就可以了,同时让prepre 指向 2, 将各部分串联起来。
pre.next = cur.next;cur.next = pre;prepre.next = cur;
接下来是第二部,指针该怎么移动。
翻转完1,2就轮到3,4了,我们想让cur指向4,pre指向3,prpre指向1
prepre = pre;cur = pre.next.next;pre = pre.next;
关键:手动模拟!
运行时间:
代码:
public class SwapNodesinPairs { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode fakeNode = new ListNode(-1); fakeNode.next = head; ListNode prepre = fakeNode, pre = head, cur = head.next; while (cur != null) { pre.next = cur.next; cur.next = pre; prepre.next = cur; if (pre.next == null || pre.next.next == null) { break; } else { prepre = pre; cur = pre.next.next; pre = pre.next; } } return fakeNode.next; }}
1 0
- Swap Nodes in Pairs 交换LinkList的相邻节点
- Swap Nodes in Pairs 链表交换相邻的节点
- 交换单链表中相邻的两个元素 Swap Nodes in Pairs
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- [LeetCode]Swap Nodes in Pairs 交换节点
- [C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)
- 24. Swap Nodes in Pairs(每两个相邻节点进行一次交换)
- LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- Swap Nodes in Pairs:交换链表数组相邻元素的值
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- 【链表&交换邻节点】Swap Nodes in Pairs
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- 24. Swap Nodes in Pairs-节点交换|指针
- LeetCode 24. Swap Nodes in Pairs(交换节点)
- LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
- [LeetCode] Swap Nodes in Pairs(成对交换节点)
- IEEE802.11协议基础知识
- Android如何保存文件到sd卡,及期间遇到的各种问题
- 错误
- IIS添加.net framework 4的支持
- tsar的使用
- Swap Nodes in Pairs 交换LinkList的相邻节点
- 定制new和delete
- Windows下的Mysql日志操作
- 无限轮播
- abas ERP – ERP行业中的“隐藏冠军”
- dos中mybatis generator自动生成出现xml parsers Error 前言中不允许有内容解决方法
- JavaScript跨域总结与解决办法
- VR/AR动手玩(一):在Android应用中集成opencv
- JS获取当前时间戳的方法