Skip to content

add:find kth element towards head of linked list #11786

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions data_structures/linked_list/kth_element_towards_head.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, data):
if not self.head:
self.head = Node(data)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(data)

def find_kth_node(self, k):
current = self.head
count = 0
while current:
count += 1
if count == k:
return current.data
current = current.next
return None

linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.append(4)
linked_list.append(5)

print(linked_list.find_kth_node(3))

Check failure on line 36 in data_structures/linked_list/kth_element_towards_head.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

data_structures/linked_list/kth_element_towards_head.py:36:36: W291 Trailing whitespace

Check failure on line 36 in data_structures/linked_list/kth_element_towards_head.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W292)

data_structures/linked_list/kth_element_towards_head.py:36:38: W292 No newline at end of file
Loading