# Data Structure – codewindow.in

## Data Structure

#### Here is an example of how to reverse a linked list in Python:

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

def __init__(self):

def reverse(self):
prev = None
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
``````

#### Here is the implementation of the algorithm in Python:

``````def has_cycle(head):
return False

while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next

return True
``````

#### Here's the implementation of the algorithm in Python:

``````def find_middle_element(head):
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
``````

#### Here is the Python code to implement the above steps:

``````class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

def mergeTwoLists(l1: Node, l2: Node) -> Node:
dummy = Node(0)
curr = dummy

while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next

if l1:
curr.next = l1
elif l2:
curr.next = l2

return dummy.next
``````

#### Here is the implementation of the above steps in Python:

``````def delete_node(node):
# check if the given node is not the last node in the linked list
if node.next is not None:
# copy the data from the next node to the node to be deleted
node.data = node.next.data
# point the next pointer of the node to be deleted to the node next to the next node
node.next = node.next.next
# delete the next node
del node.next
else:
raise ValueError("Cannot delete last node using this method")
``````

#### Here is an example implementation of a stack using a linked list in Python:

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

class Stack:
def __init__(self):
self.top = None

def push(self, data):
new_node = Node(data)
new_node.next = self.top
self.top = new_node

def pop(self):
if self.top is None:
return None
data = self.top.data
self.top = self.top.next
return data

def peek(self):
if self.top is None:
return None
return self.top.data

def isEmpty(self):
return self.top is None
``````

## We Loveto Support you

Go through our study material. Your Job is awaiting.