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

 

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

Thinking

Today, we are stepping into the linked list!

This problem mainly wants to examine how to obtain the nth node from the end of the linked list. Normally, we use the double pointers to achieve that. If you want to get the k th node from the end of the linked list, you need a pointer pointing to the head of the list, and another pointer pointing to the kth node from the beginning of the list, which is easy to get. Just iterate to the kthe node. And then move two pointers simultaneously until the latter one reaches the end of the list. Then, the first pointer now are pointing to the kth node from the end, since two pointers are always k-1 away from each other.

The linked list problems are relatively intuitive and easy to solve. This is a good practice.

Solution

What I learned

Not much honestly. Tomorrow's daily challenge is expected to still be linked-list problem. Such problems have a bunch of tricks to solve. As long as you know them and practice them well, it should not be a problem. I think the most important part is to deeply understand such data structure and try to use it in the real life projects.

By bruce

Leave a Reply

Your email address will not be published. Required fields are marked *