Swap Nodes in Pairs šŸŽÆ

beginner
22 min

Swap Nodes in Pairs šŸŽÆ

Welcome to an exciting journey through the world of Data Structures and Algorithms! Today, we're going to learn about swapping nodes in pairs, a fundamental concept that will help you understand and solve complex problems.

Understanding Linked Lists šŸ“

Before we dive into swapping nodes, let's quickly review linked lists, a common data structure we'll be working with. A linked list is a sequence of data elements, called nodes, linked using pointers. Each node contains a data part and a reference (or link) to the next node in the sequence.

python
class Node: def __init__(self, data=None): self.data = data self.next = None

Swapping Nodes in Pairs šŸ’”

Now, let's focus on our main topic: swapping nodes in pairs. This technique is useful when you need to rearrange the order of elements in a linked list.

The Algorithm šŸ“

  1. Initialize two pointers, current and next, both pointing to the head of the linked list.
  2. Create a third pointer, temp, to help us temporarily store node references.
  3. Swap the data of the nodes linked to current and next.
  4. Move the current pointer two steps forward by updating it as current = current.next.next.
  5. Move the next pointer one step forward by updating it as next = next.next.
  6. Repeat steps 3-5 until the current pointer reaches the end of the linked list (when current.next is None).

Implementation šŸ’”

Here's a complete implementation of the algorithm in Python:

python
class Node: def __init__(self, data=None): self.data = data self.next = None def swapPairs(head): if head is None or head.next is None: return head current = head next_node = current.next temp = next_node.next current.next = next_node.next next_node.next = current.next.next next_node.next.next = next_node current.next = next_node current = current.next.next while current is not None: next_node = current.next temp = next_node.next current.next = next_node.next next_node.next = current.next.next next_node.next.next = next_node current.next = next_node current = current.next.next return head # Testing the function node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node1.next = node2 node2.next = node3 node3.next = node4 result = swapPairs(node1) while result is not None: print(result.data) result = result.next

Quiz šŸŽÆ

Question: What does the swapPairs function do?

A: It finds the maximum element in a linked list B: It swaps nodes in pairs in a linked list C: It removes duplicates from a linked list Correct: B Explanation: The swapPairs function swaps nodes in pairs in a linked list.