题目
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.
思路
首先判断是否可以取到2个节点,如果可以,对这两个节点的next进行交换,同时存储交换后的第二个节点为pre,下一轮取两个节点,当交换完后,把第一个节点赋给pre.next,保证上一步和下一步链接好
Python实现
|
|