Last active
August 29, 2015 14:03
-
-
Save habina/f521508cef301ac0d18d to your computer and use it in GitHub Desktop.
2.2 Implement an algorithm to find the kth to last element of a singly linked list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
============================================================================ | |
Question : 2.2 Implement an algorithm to find the kth to last element of a singly linked list. | |
Solution : Faster pointer move forward Kth node first, then move forward to the end alone with slow pointer, | |
until faster pointer reaches the end, return slower pointer | |
Time Complexity : O(N) | |
Space Complexity: O(1) | |
Gist Link : https://gist.github.com/habina/f521508cef301ac0d18d | |
============================================================================ | |
""" | |
import random | |
class Node: | |
def __init__(self, value=None, next=None): | |
self.value = value | |
self.next = next | |
def __str__(self): | |
return chr(self.value) | |
def print_linkedList(node): | |
while node: | |
print(node) | |
node = node.next | |
def initialize_linkedList(n): | |
random.seed() | |
head = Node(random.randint(97, 122), 0) | |
n -= 1 | |
current = head | |
while(n > 0): | |
temp = Node(random.randint(97, 122), 0) | |
current.next = temp | |
current = temp | |
n -= 1 | |
return head | |
def find_kth_to_end(head, k): | |
fast = head | |
slow = head | |
for i in range(k): | |
if(fast.next): | |
fast = fast.next | |
else: | |
print("nodes are less than k") | |
return 0 | |
while(fast): | |
fast = fast.next | |
slow = slow.next | |
return slow | |
total_node = 10 | |
a = initialize_linkedList(total_node) | |
print("Original Linked List:") | |
print_linkedList(a) | |
print() | |
k = 8 | |
b = find_kth_to_end(a, k) | |
if(b): | |
print("Linked List %dth to end:", k) | |
print_linkedList(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment