24. 两两交换链表中的节点 (中等)

题目

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

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

示例:

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

解题思路

没啥思路,就是主要保存前一次两两交换的最后节点

代码


/**

 * 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 newHead = head.next;

        ListNode pre = null;

        while (head != null  && head.next != null){

            ListNode next  = head.next;

            if(pre != null){

                pre.next = next;

            }

            head.next = next.next;

            System.out.print(head.val);

            next.next = head;

            pre = head;

            head = head.next;

        }

        return newHead;

    }

}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!