佛山宽屏网站建设,js网页设计案例,渔具网站建设策划书前言,wordpress 文章 列表两两交换链表中的节点 给定一个链表#xff0c;两两交换其中相邻的节点#xff0c;并返回交换后的链表。 你不能只是单纯的改变节点内部的值#xff0c;而是需要实际的进行节点交换。 输入#xff1a;head 1-2-3-4-5-NULL 输出#xff1a;2-1-两两交换其中相邻的节点并返回交换后的链表。 你不能只是单纯的改变节点内部的值而是需要实际的进行节点交换。 输入head 1-2-3-4-5-NULL 输出2-1-4-3-5-NULL public ListNode swapPairs(ListNode head) {if (head null || head.next null) return head; //确保了以下代码至少是两个节点ListNode dummyNode new ListNode(-1);dummyNode.next head;ListNode prev dummyNode;ListNode first head;ListNode second head.next;while (second ! null) {//确保两个节交换点中只有first这一个节点就不交换ListNode next second.next;prev.next second;second.next first;//second是两个需要交换节点的最后面的那个节点first.next next;prev first;//prev总是总是两个first next;if (first null) break;second first.next;}return dummyNode.next;}