Skip to content

Commit 9e68fb7

Browse files
committed
add:kth element towards head
1 parent 40f65e8 commit 9e68fb7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Node:
2+
def __init__(self, data):
3+
self.data = data
4+
self.next = None
5+
6+
class LinkedList:
7+
def __init__(self):
8+
self.head = None
9+
10+
def append(self, data):
11+
if not self.head:
12+
self.head = Node(data)
13+
else:
14+
current = self.head
15+
while current.next:
16+
current = current.next
17+
current.next = Node(data)
18+
19+
def find_kth_node(self, k):
20+
current = self.head
21+
count = 0
22+
while current:
23+
count += 1
24+
if count == k:
25+
return current.data
26+
current = current.next
27+
return None
28+
29+
linked_list = LinkedList()
30+
linked_list.append(1)
31+
linked_list.append(2)
32+
linked_list.append(3)
33+
linked_list.append(4)
34+
linked_list.append(5)
35+
36+
print(linked_list.find_kth_node(3))

0 commit comments

Comments
 (0)