Skip to content

Latest commit

 

History

History

swapping-nodes-in-a-linked-list

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

< Previous                  Next >

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).

 

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]

Example 2:

Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]

 

Constraints:

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100

Related Topics

[Linked List] [Two Pointers]

Similar Questions

  1. Remove Nth Node From End of List (Medium)
  2. Swap Nodes in Pairs (Medium)
  3. Reverse Nodes in k-Group (Hard)

Hints

Hint 1 We can transform the linked list to an array this should ease things up
Hint 2 After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list