题目描述:给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
题目地址:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
思路:
1、递归思想,每交换相邻两个节点就进入下一次递归,边界条件是当前的第一个节点为null或第二个节点为null(此时只有一个节点不需要交换)。
2、使用一个辅助节点连接首节点,另一个辅助节点连接当前比较的第一个节点的前一个节点。
代码展示:
1、
/**
* @ClassName Solution
* @Description
* @Author Administrator
* @Date 2020/6/4 10:29
* @Version 1.0
**/
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode p = head, q = p.next, r = q.next;
q.next = p;
head = q;
p.next = swapPairs(r);
return head;
}
}
2、
/**
* @ClassName Solution1
* @Description
* @Author Administrator
* @Date 2020/6/4 10:39
* @Version 1.0
**/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode temp = new ListNode(0);
temp.next = head;
ListNode pre = temp;
ListNode firstNode, lastNode;
while (head != null && head.next != null){
firstNode = pre.next;
lastNode = firstNode.next;
pre.next = lastNode;
firstNode.next = lastNode.next;
lastNode.next = firstNode;
pre = firstNode;
head = firstNode.next;
}
return temp.next;
}
}