Swapping the node in the linked list

Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
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]
Input: head = [1], k = 1
Output: [1]
Input: head = [1,2], k = 1
Output: [2,1]
Input: head = [1,2,3], k = 2
Output: [1,2,3]
  • The number of nodes in the list is n.
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100
def swapNodes(self, head,k):
if not head:
return None
ptr1=head
while(k>1):
k-=1
ptr1=ptr1.next
ptr2=head
temp=ptr1.next
while(temp):
ptr2=ptr2.next
temp=temp.next
ptr1.val,ptr2.val=ptr2.val,ptr1.val
return head

--

--

--

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Infinite Monkey Theorem 🐒

What Does It Take to Destroy a Credit/Gift Card?

A melted credit card with a flame to it

What’s New in PHP 8.1?

Cover image for What's New in PHP 8.1?

New Market Pair: Function X (FX)

What is Good Software, Really?

5 Things I Learned During Project Phase

Brief introduction to Software Development Lifecycle(SDLC)

How to configure OSCAR in Google Kubernetes Engine — A Step-by-Step Guide

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

More from Medium

Engineering journalistic algorithms, when machines become the gatekeepers of news

India’s fintech companies struggle for an alternative to Aadhaar

Everything you want to know about the Stanford part-time MSCS

Machine Learning Job Search in 2021