题目: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.
解释:给你一个链表,从表头开始,每两个节点交换顺序,比如1->2->3->4,那么1和2交换顺序,3和4交换顺序,然后把交换顺序之后的这个表的表头返回。要求您的算法应该使用不变的内存(就是说内存不能不断地递增),而且不能改变节点的值,它们只是顺序改变了。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode firstNode = head;
ListNode secondNode = head.next;
ListNode thirdNode = head.next.next;
firstNode.next = swapPairs(thirdNode);
secondNode.next = firstNode;
return secondNode;
}
}