Skip to content

Commit

Permalink
feat(datastructure): linked list pair wise swap
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina committed Jan 18, 2024
1 parent 446ff62 commit 00e2ce8
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
35 changes: 34 additions & 1 deletion datastructures/linked_lists/singly_linked_list/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,14 @@ def is_palindrome(self) -> bool:

return True

def pairwise_swap(self) -> SingleNode:
def pairwise_swap(self) -> Optional[SingleNode]:
"""
Swaps nodes in pairs.
However, this swaps the values of the nodes in pairs and not the pointers
Return:
SingleNode: new head node or None if no head exists.
"""
# nothing to do here
if not self.head:
return self.head
Expand All @@ -552,6 +559,32 @@ def pairwise_swap(self) -> SingleNode:
# at this point, the linked list has been swapped in pairs
return self.head

def pairwise_swap_two(self) -> Optional[SingleNode]:
"""
Swaps nodes in pairs without swapping the values in the nodes.
Return:
SingleNode: new head node or None if no head exists.
"""
# nothing to do here
if not self.head:
return self.head

start = SingleNode(None)
start.next = self.head
self.head = start

while self.head.next and self.head.next.next:
temp = self.head.next.next

self.head.next.next = temp.next
temp.next = self.head.next

self.head.next = temp
self.head = self.head.next.next

return start.next

def swap_nodes_at_kth_and_k_plus_1(self, k: int) -> SingleNode:
a, b = self.head, self.head

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import unittest

from . import SinglyLinkedList, SingleNode


class SinglyLinkedListPairwiseTest(unittest.TestCase):
def test_empty_list(self):
linked_list = SinglyLinkedList()
head = linked_list.pairwise_swap()
self.assertIsNone(head)

def test_two(self):
"""1 -> 2 -> 3 -> 4 should become 2 -> 1 -> 4 -> 3"""
linked_list = SinglyLinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.append(4)

head = linked_list.pairwise_swap_two()

expected_head = SingleNode(2, next_=SingleNode(1, next_=SingleNode(4, next_=SingleNode(3))))

self.assertEqual(head, expected_head)

def test_three(self):
"""7 -> 2 -> 1 should become 2 -> 7 -> 1"""
linked_list = SinglyLinkedList()
linked_list.append(7)
linked_list.append(2)
linked_list.append(1)

head = linked_list.pairwise_swap_two()

expected_head = SingleNode(2, next_=SingleNode(7, next_=SingleNode(1)))

self.assertEqual(head, expected_head)


if __name__ == "__main__":
unittest.main()

0 comments on commit 00e2ce8

Please sign in to comment.