|
| 1 | +# Template for linked list node class |
| 2 | +class LinkedListNode: |
| 3 | + def __init__(self, data, next=None): |
| 4 | + self.data = data |
| 5 | + self.next = next |
| 6 | + |
| 7 | +# Template for the linked list |
| 8 | +class LinkedList: |
| 9 | + def __init__(self): |
| 10 | + self.head = None |
| 11 | + |
| 12 | + # Method to insert a node at the head of the linked list |
| 13 | + def insert_node_at_head(self, node): |
| 14 | + if self.head: |
| 15 | + node.next = self.head |
| 16 | + self.head = node |
| 17 | + |
| 18 | + # Method to create a linked list from a list of values |
| 19 | + def create_linked_list(self, values): |
| 20 | + for value in reversed(values): |
| 21 | + self.insert_node_at_head(LinkedListNode(value)) |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +def remove_nth_last_node(head, n): |
| 28 | + right = head |
| 29 | + left = head |
| 30 | + |
| 31 | + # Move the right pointer forward n steps |
| 32 | + for i in range(n): |
| 33 | + right = right.next |
| 34 | + |
| 35 | + # If right is None after moving n steps, we need to remove the head (i.e. n exceeds length of linked list) |
| 36 | + if right is None: |
| 37 | + return head.next # Removing the head |
| 38 | + |
| 39 | + # Move both pointers forward until right reaches the end |
| 40 | + while right.next is not None: |
| 41 | + right = right.next |
| 42 | + left = left.next |
| 43 | + |
| 44 | + # Remove the Nth node from the end |
| 45 | + left.next = left.next.next |
| 46 | + |
| 47 | + return head |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +# Function to print the linked list |
| 54 | +def print_list_with_forward_arrow(head): |
| 55 | + current = head |
| 56 | + while current: |
| 57 | + print(current.data, end=" -> " if current.next else "") |
| 58 | + current = current.next |
| 59 | + print() |
| 60 | + |
| 61 | +# Driver code |
| 62 | +def main(): |
| 63 | + lists = [ |
| 64 | + [23, 89, 10, 5, 67, 39, 70, 28], |
| 65 | + [34, 53, 6, 95, 38, 28, 17, 63, 16, 76], |
| 66 | + [288, 224, 275, 390, 4, 383, 330, 60, 193], |
| 67 | + [1, 2, 3, 4, 5, 6, 7, 8, 9], |
| 68 | + [69, 8, 49, 106, 116, 112, 104, 129, 39, 14, 27, 12] |
| 69 | + ] |
| 70 | + n = [4, 1, 6, 9, 11] |
| 71 | + |
| 72 | + for i in range(len(n)): |
| 73 | + input_linked_list = LinkedList() |
| 74 | + input_linked_list.create_linked_list(lists[i]) |
| 75 | + print(i + 1, ". Linked List:\t", end='') |
| 76 | + print_list_with_forward_arrow(input_linked_list.head) |
| 77 | + print("n = ", n[i]) |
| 78 | + result = remove_nth_last_node(input_linked_list.head, n[i]) |
| 79 | + print("Updated Linked List:\t", end='') |
| 80 | + print_list_with_forward_arrow(result) |
| 81 | + print("-" * 100) |
| 82 | + |
| 83 | +if __name__ == '__main__': |
| 84 | + main() |
0 commit comments