您的当前位置:首页Leetcode # 24:两两交换链表中的节点[hard]

Leetcode # 24:两两交换链表中的节点[hard]

2023-05-02 来源:小侦探旅游网

描述

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

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

示例

示例:

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

思路

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 || head.next == null){
            return head;
        }
        //先拿到头结点
        ListNode res = head.next;
        //保存每组的前一个节点
        ListNode preNode = null;
        while(head.next != null){
            if(preNode != null){
                preNode.next = head.next;
            }
            preNode = head;
            ListNode nextGroupNode = head.next.next;
            head.next.next = head;
            head.next = nextGroupNode;
            head = nextGroupNode;
            if(head == null){
                break;
            }
        }
        return res;
    }
}

 

因篇幅问题不能全部显示,请点此查看更多更全内容