Leetcode #24 两两交换链表中的节点

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 递归解法
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        // 递归解法,当head为null或下一个为null时,说明到了最后一个,返回head
        if(head == null || head.next == null) {
            return head;
        }
        // 定义两个引用
        ListNode first = head;
        ListNode second = head.next;
        // 通过递归设置交换后第二个节点的next
        first.next = swapPairs(second.next);
        // 设置交换后第一个节点的next
        second.next = first;
        // 返回头节点
        return second;
    }
}
  • 循环解法
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode hair = new ListNode(0);
        hair.next = head;
        ListNode preNode = hair;
        while(head != null && head.next != null) {
            // 定义first和second引用
            ListNode first = head;
            ListNode second = head.next;
            // 前一个节点的next指向second(交换后第一个节点)
            preNode.next = second;
            // 先让交换后第二个节点的next指向后续节点(这次循环结束后可以后移)
            first.next = second.next;
            // 交换后第一个节点的next指向交换后第二个
            second.next = first;
            // 保存需要处理的节点
            preNode = first;
            // 后移(因为first的next正确指向下一个未处理的节点)
            head = head.next;
        }
        return hair.next;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务