Problem: 24. 两两交换链表中的节点
复杂度
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)
Code
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode swapPairs(ListNode head){if (head == null)return head;ListNode pre = new ListNode(0, head);//前驱节点 执行 firstListNode ans = pre;ListNode first = pre.next;// 第一个节点while (first.next != null){ListNode second = first.next;// 第二个节点ListNode tail = second.next;// 后续节点//交换第一、二个节点pre.next = second;second.next = first;//把后续的节点接到交换后的 first 节点上first.next = tail;pre = first;// pre 为交换后靠后的 first节点first = pre.next;//first = pre.next;if (tail == null)//后续无节点了直接结束break;}return ans.next;}
}