Skip to content

Commit 0ffd517

Browse files
finished 2.2
1 parent 5d12106 commit 0ffd517

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
"""
2+
Return Kth to Last: Implement an algorithm to find the kth to last element of
3+
a singly linked list.
4+
Hints:#8, #25, #41, #67, #126
5+
"""
6+
7+
class Node:
8+
#Singly link list
9+
def __init__(self,data):
10+
self.data = data
11+
self.next = None
12+
13+
class linklist:
14+
#linkList class
15+
def __init__(self):
16+
self.head = None
17+
self.size = 0
18+
19+
def push(self,data):
20+
node = Node(data)# create a new node
21+
22+
if self.head == None: #check to see if the head node is empty
23+
self.head = node # If its empty add it to the new node
24+
self.size = 1
25+
return
26+
#if the head of the linklist is filled
27+
28+
current = self.head
29+
while current.next is not None:#Check the current postion is empty
30+
#Move to the next line if nothing is there
31+
current = current.next
32+
33+
34+
current.next = node #point self.head to a new node
35+
self.size+=1
36+
37+
38+
39+
40+
def lenght(self):
41+
#note the count doesn't start at zero
42+
cur = self.head
43+
counter = 0
44+
while cur is not None:
45+
counter+=1
46+
cur = cur.next
47+
print('Linklist len: '+str(counter))
48+
return counter
49+
50+
def printList(self):
51+
curr = self.head
52+
elem = []
53+
54+
while(curr != None):
55+
elem.append(curr.data)
56+
curr = curr.next
57+
print(elem)
58+
#1->2->3
59+
def remove_node(self,data):
60+
#1->2->3
61+
curr = self.head
62+
if curr is not None and curr.data == data:
63+
self.head = curr.next
64+
curr = None
65+
#look for the node that has the data we are looking for
66+
while curr is not None:
67+
if curr.data == data:
68+
break
69+
prev = curr
70+
curr = curr.next
71+
72+
#if data isn't found just reutrn
73+
if(curr == None):
74+
return
75+
76+
#allow us to unlink the nodes
77+
prev.next = curr.next
78+
curr = None
79+
80+
def Kth_to_Last(self,num):
81+
counter = 1 # We need to keep track where we are
82+
curr = self.head
83+
goal = self.size - num# kth to last element
84+
while curr is not None:
85+
if goal == counter:
86+
return curr.data
87+
counter+=1
88+
curr = curr.next
89+
90+
91+
92+
93+
94+
95+
llist = linklist()
96+
llist.push(1)
97+
llist.push(2)
98+
llist.push(3)
99+
llist.push(4)
100+
llist.push(5)
101+
llist.printList()
102+
103+
llist.lenght()
104+
print(llist.Kth_to_Last(1))# should return 4
105+
print(llist.Kth_to_Last(2))# should return 4
106+
print(llist.Kth_to_Last(3))# should return 4

0 commit comments

Comments
 (0)