mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 04:36:08 -04:00
Create swap_every_two_nodes.py
This commit is contained in:
parent
eb7bc74843
commit
84f2a8fe94
24
linked_lists/swap_every_two_nodes.py
Normal file
24
linked_lists/swap_every_two_nodes.py
Normal file
@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
|
||||
class ListNode:
|
||||
def __init__(self, val=0, next=None):
|
||||
self.val = val
|
||||
self.next = next
|
||||
|
||||
|
||||
def swap_pairs(head: Optional[ListNode]) -> Optional[ListNode]:
|
||||
if not head or not head.next:
|
||||
return head
|
||||
|
||||
## nodes to be swapped
|
||||
first_node = head
|
||||
second_node = head.next
|
||||
|
||||
# swapping
|
||||
first_node.next = swap_pairs(second_node.next)
|
||||
second_node.next = first_node
|
||||
|
||||
return second_node
|
Loading…
x
Reference in New Issue
Block a user