https://leetcode.com/problems/swap-nodes-in-pairs/description/
题目描述: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:题目要求交换相邻的链表节点。
使用递归交换相邻的两个节点,当当前节点或下一个节点为空时停止递归。
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode temp = head.next;
head.next = swapPairs(head.next.next);
temp.next = head;
return temp;
}
解题思路2:设置一个跟踪节点,每次移动两步,依次交换相邻节点。
public ListNode swapPairs2(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode current = dummyNode;
while(current.next!=null&¤t.next.next!=null){
ListNode first = current.next;
ListNode second = current.next.next;
first.next = second.next;
second.next = first;
current.next = second;
current = current.next.next;
}
return dummyNode.next;
}