1721. Swapping Nodes in a Linked List
Description
You are given the head
of a linked list, and an integer k
.
Return the head of the linked list after swapping the values of the kth
node from the beginning and the kth
node from the end (the list is 1-indexed).
Constraints
The number of nodes in the list is
n
.1 <= k <= n <= 105
0 <= Node.val <= 100
Approach
Links
GeeksforGeeks
ProgramCreek
YouTube
Examples
Input: head = [1, 2, 3, 4, 5], k = 2
Output: [1, 4, 3, 2, 5]
Solutions
// 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;
}
}
Follow up
Last updated
Was this helpful?