[LeetCode] Swap Nodes in Pairs
LeetCode in swap nodes Pairs
2023-09-11 14:17:25 时间
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:每次交换cur1和cur2,使用dummy保证了pre的初始赋值的正确性,同时,注意next有可能为空。
/** * 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; ListNode dummy(-1); dummy.next = head; ListNode* pre = &dummy; ListNode* cur1 = head; ListNode* cur2 = head->next; ListNode* next = NULL; // swap cur1 and cur2 while(cur1 && cur2) { next = cur2->next; pre->next = cur2; cur2->next = cur1; cur1->next = next; pre = cur1; cur1 = next; // next may be NULL if(next == NULL) break; else cur2 = next->next; } return dummy.next; } };
相关文章
- Java实现 LeetCode 835 图像重叠(暴力)
- Java实现 LeetCode 827 最大人工岛(DFS+暴力模拟)
- Java实现 LeetCode 593 有效的正方形(判断正方形)
- Java实现 LeetCode 446 等差数列划分 II - 子序列
- Java实现 LeetCode 74 搜索二维矩阵
- Java实现 LeetCode 57 插入区间
- (LeetCode 153)Find Minimum in Rotated Sorted Array
- LeetCode(105):从前序与中序遍历序列构造二叉树
- 每日一道 LeetCode (16):求 x 的平方根
- (LeetCode 153)Find Minimum in Rotated Sorted Array
- [LeetCode] Longest Increasing Path in a Matrix
- 已解决FutureWarning: The default value of regex will change from True to False in a future version. In
- LeetCode 383. 赎金信
- Leetcode 3. 无重复字符的最长子串(超出时间限制的情况下)
- LeetCode-Reverse Words in a String
- LeetCode:Populating Next Right Pointers in Each Node
- Spark SQL 源代码分析之 In-Memory Columnar Storage 之 in-memory query
- [LeetCode] Delete Node in a Linked List
- VC2015提示warning C4996: 'MBCS_Support_Deprecated_In_MFC': MBCS support in MFC is dep
- leetcode 783. Minimum Distance Between BST Nodes 以及同样的题目 530. Minimum Absolute Difference in BST
- leetcode 378. Kth Smallest Element in a Sorted Matrix
- 【Mac系统】Vscode使用LeetCode插件报错‘leetcode.toggleLeetCodeCn‘ not found