24. 【中等】两两交换链表中的节点

24. 【中等】两两交换链表中的节点


链接

题目描述

在这里插入图片描述

1.递归

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null){
            return head;
        }
        if(head.next == null){
            return head;
        }
        ListNode cur = head;
        ListNode next = cur.next;
        ListNode temp = next.next;
        next.next = cur;
        cur.next = swapPairs(temp);
        return next;
    }
}

2.非递归

对当前节点 temp ,去交换当前节点的下两个节点,交换完了把 temp 往后移动

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null){
            return head;
        }
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode temp = pre;
        while(temp.next != null && temp.next.next != null){
            ListNode start = temp.next;
            ListNode end = temp.next.next;
            temp.next = end;
            start.next = end.next;
            end.next = start;
            temp = start;
        }
        return pre.next;
    }
}
发布了55 篇原创文章 · 获赞 1 · 访问量 876

猜你喜欢

转载自blog.csdn.net/weixin_42469108/article/details/103651445