Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

NAME : ANKIT RAJ

UID : 21BCS8715
SECTION/ GROUP : 21BCS-CC-652-B
SUBJECT : IT SKILLS

DAY-4

CODE:
1. Partition List
class Solution:
def hasCycle(self, head: ListNode) -> bool:
# Initialize slow and fast pointers
slow = head
fast = head

# Traverse the linked list


while fast and fast.next:
slow = slow.next
fast = fast.next.next

# Check if slow and fast pointers meet


if slow == fast:
return True

# No cycle found
return False

2. Insertion Sort List


class Solution:
def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Create a dummy node for the sorted list
dummy = ListNode(float('-inf'))

# Traverse the original list


current = head
while current:
# Save the next node to be processed
next_node = current.next

# Find the correct position to insert current node in the sorted list
prev = dummy
while prev.next and prev.next.val < current.val:
prev = prev.next

# Insert current node into the sorted list


current.next = prev.next
prev.next = current

# Move to the next node in the original list


current = next_node

return dummy.next

3. Swap Nodes in Pairs


class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Create a dummy node to handle edge cases
dummy = ListNode(0)
dummy.next = head
prev = dummy

# Iterate through the list and swap pairs of nodes


while prev.next and prev.next.next:
first_node = prev.next
second_node = prev.next.next

# Swap the nodes


first_node.next = second_node.next
second_node.next = first_node
prev.next = second_node

# Move to the next pair of nodes


prev = first_node

return dummy.next

4. Palindrome Linked List


class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return True

# Find the middle of the linked list


slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next

# Reverse the second half of the linked list


second_half = self.reverseLinkedList(slow.next)

# Compare the first half with the reversed second half


first_half = head
while second_half:
if first_half.val != second_half.val:
return False
first_half = first_half.next
second_half = second_half.next

return True

def reverseLinkedList(self, head: ListNode) -> ListNode:


prev_node = None
while head:
next_node = head.next
head.next = prev_node
prev_node = head
head = next_node
return prev_node

5. Linked List Cycle


class Solution:
def hasCycle(self, head: ListNode) -> bool:
# Initialize slow and fast pointers
slow = head
fast = head

# Traverse the linked list


while fast and fast.next:
slow = slow.next
fast = fast.next.next

# Check if slow and fast pointers meet


if slow == fast:
return True

# No cycle found
return False

Outputs:

You might also like