版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84426887
文章目录
1. 题目描述:
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.
2. 思路分析:
题目的意思是将一个链表按照顺序每两个进行翻转。
可以用递归的思路来解决问题,非常简单,代码简洁。取出前2个节点调换一下顺序,剩下的节点进行递归调用即可。
3. Java代码:
源代码
:见我GiHub主页
代码:
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tempNode = head.next;
head.next = swapPairs(tempNode.next);
tempNode.next = head;
return tempNode;
}