Created
September 15, 2022 19:17
-
-
Save sumeet/8795dfb54e1b76f6970892e3f5c094b0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LL: | |
@classmethod | |
def from_list(cls, vals): | |
if not vals: | |
raise "LL must have at least one element" | |
root = cls(vals[0]) | |
cur = root | |
for val in vals[1:]: | |
cur.next = cls(val) | |
cur = cur.next | |
return root | |
def __init__(self, val, next=None): | |
self.val = val | |
self.next = next | |
def __repr__(self): | |
return f'<LL: val={self.val} next={self.next}>' | |
def print(self): | |
head = self | |
l = [] | |
while head: | |
l.append(head.val) | |
head = head.next | |
print(l) | |
def swap_nodes(ll, k): | |
root = ll | |
a = None | |
len = 1 | |
while ll.next: | |
if len == k: | |
a = ll | |
len +=1 | |
ll = ll.next | |
b = root | |
for _ in range(len - k): | |
b = b.next | |
a.val, b.val = b.val, a.val | |
ll = LL.from_list([1, 2, 3, 4, 5]) | |
ll.print() | |
swap_nodes(ll, 2) | |
ll.print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment