24. Swap Nodes in Pairs(交换链表中的相邻结点)

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:

Given 1->2->3->4, you should return the list as 2->1->4->3.

题目要求:不能修改结点的 val 值,O(1) 空间复杂度。

方法一:双指针
其实这题用的是多指针,这里暂且叫双指针。因为head指向的是链表中第一个数1。第一个数需要和第二个数换,
所以我得额外定义一个指针node记录第一个结点。同时我还需要一个移动的指针pre参与交换。

时间复杂度:o(n) 空间复杂度:o(1)

 


posted on 2019-03-19 11:23  shaer  阅读(101)  评论(0编辑  收藏  举报

导航