题目的链接在这里:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
题目大意
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
一、示意图
二、解题思路
使用递归和非递归
非递归
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
//先进行边界判断
if(head==null)
return null;
if(head.next==null)
return head;
//如果是非递归的化
//这边要进行返回
ListNode result=head;
while (head!=null&&head.next!=null){
//一次进行两次变化 直接换值比较好吧
int temp=head.val;
head.val=head.next.val;
head.next.val=temp;
//然后向后退两个
head=head.next.next;
}
return result;
}
}
递归
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
//先进行边界判断
if(head==null)
return null;
if(head.next==null)
return head;
//应该是可以用到递归的
//前面的排除了next等于null的值
//所以只需要交换前面两个 然后后面的就递归调用就行了
ListNode temp=head.next;
//这里就用到了递归
head.next=swapPairs(temp.next);
temp.next=head;
return temp;
}
}