1721. Swapping Nodes in a Linked List Medium
1/**
2 * [1721] Swapping Nodes in a Linked List
3 *
4 * You are given the head of a linked list, and an integer k.
5 * Return the head of the linked list after swapping the values of the k^th node from the beginning and the k^th node from the end (the list is 1-indexed).
6 *
7 * Example 1:
8 * <img alt="" src="https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg" style="width: 400px; height: 112px;" />
9 * Input: head = [1,2,3,4,5], k = 2
10 * Output: [1,4,3,2,5]
11 *
12 * Example 2:
13 *
14 * Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
15 * Output: [7,9,6,6,8,7,3,0,9,5]
16 *
17 *
18 * Constraints:
19 *
20 * The number of nodes in the list is n.
21 * 1 <= k <= n <= 10^5
22 * 0 <= Node.val <= 100
23 *
24 */
25pub struct Solution {}
26use crate::util::linked_list::{ListNode, to_list};
27
28// problem: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
29// discuss: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/?currentPage=1&orderBy=most_votes&query=
30
31// submission codes start here
32
33// Definition for singly-linked list.
34// #[derive(PartialEq, Eq, Clone, Debug)]
35// pub struct ListNode {
36// pub val: i32,
37// pub next: Option<Box<ListNode>>
38// }
39//
40// impl ListNode {
41// #[inline]
42// fn new(val: i32) -> Self {
43// ListNode {
44// next: None,
45// val
46// }
47// }
48// }
49impl Solution {
50 pub fn swap_nodes(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
51 Some(Box::new(ListNode::new(0)))
52 }
53}
54
55// submission codes end
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn test_1721() {
63 }
64}
65
Back
© 2025 bowen.ge All Rights Reserved.