「LeetCode」24. 两两交换链表中的节点
2023-09-27 14:27:52 时间
- 两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
题解:
/**
* 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 hair = new ListNode(-1,head);
ListNode pre = hair;
while (pre.next != null && pre.next.next != null) {
ListNode one =pre.next;
ListNode two =pre.next.next;
one.next = two.next;
two.next = one;
pre.next = two;
pre = one;
}
return hair.next;
}
}
相关文章
- Leetcode: Min Stack
- 【Leetcode】143. 重排链表(中等)
- 【Leetcode】138. 复制带随机指针的链表(中等)
- 【python】leetcode 141. 环形链表
- [LeetCode]剑指 Offer 06. 从尾到头打印链表
- 【Java数据结构与算法】LeetCode 0019. 删除链表的倒数第N个结点
- 【Java数据结构与算法】LeetCode 0024.两两交换链表中的节点
- 145、【动态规划】leetcode ——70. 爬楼梯:暴力法+动态规划(C++版本)
- leetcode竞赛记录-第63场周赛
- 【LeetCode】211. Add and Search Word - Data structure design
- 【leetcode】114: 二叉树展开为链表
- [LeetCode] 267. Palindrome Permutation II 回文全排列之二
- [LeetCode] 18. 4Sum 四数之和
- [LeetCode] 92. Reverse Linked List II 倒置链表之二
- leetcode算法206.反转链表
- leetcode算法203.移除链表元素