-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Matt
committed
Jul 9, 2018
1 parent
c6e0d0c
commit 12757cd
Showing
2 changed files
with
83 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
class Node: | ||
|
||
def __init__(self, val): | ||
self.val = val | ||
self.next = None | ||
|
||
def traverse(self): | ||
n = self | ||
while n is not None: | ||
print n.val | ||
n = n.next | ||
|
||
def delete(self, node): | ||
n = self | ||
while n.next is not node: | ||
n = n.next | ||
|
||
n.next = node.next | ||
|
||
def kth_from_last(self, count): | ||
n = self | ||
ref = self | ||
|
||
i = 1 | ||
while i < count: | ||
ref = ref.next | ||
i += 1 | ||
|
||
while ref.next is not None: | ||
n = n.next | ||
ref = ref.next | ||
|
||
return n |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
from app.linked_list import Node | ||
|
||
|
||
def test_add_nodes(capfd): | ||
node1 = Node(1) | ||
node2 = Node(2) | ||
node3 = Node(3) | ||
|
||
node1.next = node2 | ||
node2.next = node3 | ||
|
||
node1.traverse() | ||
out, err = capfd.readouterr() | ||
assert out == '1\n2\n3\n' | ||
|
||
|
||
def test_delete_node(capfd): | ||
node1 = Node(1) | ||
node2 = Node(2) | ||
node3 = Node(3) | ||
|
||
node1.next = node2 | ||
node2.next = node3 | ||
|
||
node1.delete(node2) | ||
node1.traverse() | ||
out, err = capfd.readouterr() | ||
assert out == '1\n3\n' | ||
|
||
node1.delete(node3) | ||
node1.traverse() | ||
out, err = capfd.readouterr() | ||
assert out == '1\n' | ||
|
||
|
||
def test_kth_from_last(): | ||
node1 = Node(1) | ||
node2 = Node(2) | ||
node3 = Node(3) | ||
node4 = Node(4) | ||
node5 = Node(5) | ||
|
||
node1.next = node2 | ||
node2.next = node3 | ||
node3.next = node4 | ||
node4.next = node5 | ||
|
||
assert node1.kth_from_last(2) == node4 | ||
assert node1.kth_from_last(1) == node5 | ||
assert node1.kth_from_last(5) == node1 |