题目描述(难度中等)
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
1 | Given 1->2->3->4, you should return the list as 2->1->4->3. |
方法一:遍历一遍链表
链表改变顺序的题目,通用的方法论是先找出一次需要改变指向的节点数量。交换相邻节点需要改变current(相邻节点前节点的前节点),first(相邻节点前节点),second(相邻节点后节点)。current在链表头部自定义一个初始值为0的节点。
上图中展示了链表指向的过程,三个节点都需要进行重定向,一次循环后的结果:
第二次循环继续将current往后平移两个单位,继续执行循环赋值:
得到循环赋值结果:
方法一代码
分析了上图之后,代码实现较为简单:
1 | public ListNode swapPairsMoreClear(ListNode head){ |