Problem: 24. 两两交换链表中的节点
思路
画图理解
解题方法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cCH6R09g-1679156501053)(https://pic.leetcode.cn/1679149347-broYyK-%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230318222218.jpg)]
复杂度
- 时间复杂度:
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) {
ListNode dummyHead = new ListNode(-1,head);
ListNode cur = dummyHead;
while(cur.next != null && cur.next.next != null){
ListNode firstNode = cur.next;
ListNode temp = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = firstNode;
firstNode.next = temp;
cur = cur.next.next;
}
return dummyHead.next;
}
}