# Python3 program to reverse a linked list
# without affecting special characters
# Link list node
class Node:
def __init__(self, x):
self.data = x
self.next = None
# Function to reverse the linked list
# without affecting special characters
def reverse(head_ref, size):
current = head_ref
TEMP_ARR = [0 for i in range(256)]
i = 0
# Traverse the linked list and insert
# linked list elements to TEMP_ARR
while (current != None):
# If the current data is any alphabet than
# store it in to TEMP_ARR
if ((ord(current.data) >= 97 and
ord(current.data) <= 122) or
(ord(current.data) >= 65 and
ord(current.data) <= 90)):
TEMP_ARR[i]= current.data
i += 1
current = current.next
# Else increase the node position
else:
current = current.next
current = head_ref
# Traverse the linked list again
while (current != None):
# If current character is an alphabet
# than replace the current element in
# the linked list with the last element
# of the TEMP_ARR
if ((ord(current.data) >= 97 and
ord(current.data) <= 122) or
(ord(current.data) >= 65 and
ord(current.data) <= 90)):
i = i - 1
current.data = TEMP_ARR[i]
current = current.next
# Else increase the node
else:
current = current.next
return head_ref
# Function to push a node
def push(head_ref, new_data):
# Allocate node
#new_node = (struct Node*)malloc(sizeof(struct Node));
# Put in the data
new_node = Node(new_data)
# Link the old list of the new node
new_node.next = head_ref
# Move the head to point to the new node
head_ref = new_node
return head_ref
# Function to print linked list
def printList(head):
temp = head
while (temp != None):
print(temp.data, end = "")
temp = temp.next
# Driver code
if __name__ == '__main__':
# Start with the empty list
head = None
head = push(head, 's')
head = push(head, '$')
head = push(head, 'k')
head = push(head, 'e')
head = push(head, 'e')
head = push(head, '@')
head = push(head, '#')
head = push(head, 'g')
head = push(head, 'r')
head = push(head, 'o')
head = push(head, 'f')
head = push(head, 's')
head = push(head, '$')
head = push(head, 'k')
head = push(head, 'e')
head = push(head, 'e')
head = push(head, 'g')
print("Given linked list: ", end = "")
printList(head)
head = reverse(head, 13)
print("\nReversed Linked list: ", end = "")
printList(head)
# This code is contributed by mohit kumar 29