How to solve Swap Nodes in Pairs problem in LeetCode?

2026-06-09 06:274阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计376个文字,预计阅读时间需要2分钟。

How to solve Swap Nodes in Pairs problem in LeetCode?

目录- 题目链接- 注意点- 解法小总结- 题目链接- 注意点- 解法 - 解法一:维护三个指针 - 时间复杂度 - 空间复杂度

题目链接:Swap Nodes in Pairs - LeetCode注意点:考虑链表为空或只有一个节点的情况,以及如何处理相邻节点交换。解法小总结:通过维护三个指针,调整相邻节点的next指针,实现节点交换。

目录题目链接注意点解法小结题目链接SwapNodesinPairs-LeetCode注意点考虑链表为空解法解法一:维护三个指针,前中后,调换这三个位置的next指针即可。时间复杂度

目录

  • 题目链接
  • 注意点
  • 解法
  • 小结

题目链接

Swap Nodes in Pairs - LeetCode

How to solve Swap Nodes in Pairs problem in LeetCode?

注意点
  • 考虑链表为空

解法

解法一:维护三个指针,前中后,调换这三个位置的next指针即可。时间复杂度O(n)

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* swapPairs(ListNode* head) { if(head == NULL) return NULL; auto p = new ListNode(0); p->next = head; ListNode* pre = p; ListNode* cur = head; ListNode* next = head->next; while(cur != NULL cur->next = next->next; next->next = cur; pre = cur; cur = cur->next; if(cur != NULL) next = cur->next; } return p->next; }};

小结
  • 链表是很常见的一种数据结构,要花点时间专门研究一下。

本文共计376个文字,预计阅读时间需要2分钟。

How to solve Swap Nodes in Pairs problem in LeetCode?

目录- 题目链接- 注意点- 解法小总结- 题目链接- 注意点- 解法 - 解法一:维护三个指针 - 时间复杂度 - 空间复杂度

题目链接:Swap Nodes in Pairs - LeetCode注意点:考虑链表为空或只有一个节点的情况,以及如何处理相邻节点交换。解法小总结:通过维护三个指针,调整相邻节点的next指针,实现节点交换。

目录题目链接注意点解法小结题目链接SwapNodesinPairs-LeetCode注意点考虑链表为空解法解法一:维护三个指针,前中后,调换这三个位置的next指针即可。时间复杂度

目录

  • 题目链接
  • 注意点
  • 解法
  • 小结

题目链接

Swap Nodes in Pairs - LeetCode

How to solve Swap Nodes in Pairs problem in LeetCode?

注意点
  • 考虑链表为空

解法

解法一:维护三个指针,前中后,调换这三个位置的next指针即可。时间复杂度O(n)

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* swapPairs(ListNode* head) { if(head == NULL) return NULL; auto p = new ListNode(0); p->next = head; ListNode* pre = p; ListNode* cur = head; ListNode* next = head->next; while(cur != NULL cur->next = next->next; next->next = cur; pre = cur; cur = cur->next; if(cur != NULL) next = cur->next; } return p->next; }};

小结
  • 链表是很常见的一种数据结构,要花点时间专门研究一下。