Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
2023-09-14 09:07:57 时间
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.
/** * 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 || head->next == NULL) return head; ListNode dummy(0); ListNode *tail = &dummy; ListNode *pre = head; ListNode *cur = NULL; ListNode *nxt = NULL; while(pre != NULL) { cur = pre->next; if(cur != NULL) { nxt = cur->next; cur->next = pre; pre->next = NULL; tail->next = cur; tail = pre; pre = nxt; } else { tail->next = pre; return dummy.next; } } return dummy.next; } };
相关文章
- Java实现 LeetCode 783 二叉搜索树节点最小距离(遍历)
- Java实现 LeetCode 714 买卖股票的最佳时机含手续费(动态规划 || 迭代法)
- Java实现 LeetCode 671 二叉树中第二小的节点(遍历树)
- Java实现 LeetCode 495 提莫攻击
- Java实现 LeetCode 354 俄罗斯套娃信封问题
- Java实现 LeetCode 342 4的幂
- Java实现 LeetCode 327 区间和的个数
- Java实现 LeetCode 237 删除链表中的节点
- Java实现 LeetCode 222 完全二叉树的节点个数
- Java实现 LeetCode 222 完全二叉树的节点个数
- Java实现 LeetCode 162 寻找峰值
- Java实现 LeetCode 146 LRU缓存机制
- Java实现 LeetCode 24 两两交换链表中的节点
- Java实现 LeetCode 24 两两交换链表中的节点
- Java实现 LeetCode 19删除链表的倒数第N个节点
- LeetCode(72):编辑距离
- Leetcode.剑指 Offer II 022 链表中环的入口节点
- LeetCode-905. 按奇偶排序数组【数组,双指针,排序】
- ( “树” 之 DFS) 671. 二叉树中第二小的节点 ——【Leetcode每日一题】
- 【LeetCode Python实现】329. 矩阵中的最长递增路径(困难)
- Leetcode 1535. 找出数组游戏的赢家(尽力了)
- Leetcode 2000. 反转单词前缀
- [LeetCode] 24. Swap Nodes in Pairs ☆☆☆(链表,相邻两节点交换)
- [LeetCode]Linked List Cycle
- 【Leetcode刷题Python】剑指 Offer 18. 删除链表的节点
- LeetCode 768. 最多能完成排序的块 II
- 【LeetCode】查找和最小的K对数字
- 【LeetCode】求根节点到叶节点数字之和