Skip to content

Latest commit

 

History

History
29 lines (24 loc) · 880 Bytes

24.md

File metadata and controls

29 lines (24 loc) · 880 Bytes

LeetCode 24 Swap Nodes in Pairs——medium

Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
思路:
方法一:循环
1、一对一对逆转、头节点改变、设定dummy
2、需要一个p节点来记录head前一个节点
3、将每一对逆转好之后,初始化下一次需要的信息
即:p=head; head = head.next

方法二:递归
1、假设后面的已经通过递归逆转好了得到p
2、那只需要将目前的一对逆转好便可以返回了。