-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.py
More file actions
100 lines (68 loc) · 1.9 KB
/
linked_list.py
File metadata and controls
100 lines (68 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self) -> str:
return str(self.data)
# def get_nth_from_end(head, n):
# if head is None:
# return
# currHead = head
# currNext = head.next
# i = 0
# get_nth_from_end(currNext, n)
# i += 1
# if i == n:
# return currHead.data
def printNthFromLast(head, N):
def get_nth_from_end(head, n, prevNode=None):
if (head == None):
return 0
temp = get_nth_from_end(head.next, n, head)
if (temp == n):
if prevNode:
prevNode.next = head.next
return temp + 1
tempVal = get_nth_from_end(head, N)
if tempVal == N:
head = head.next
return head
def print_linked_list(head):
curr = head
while curr is not None:
print(curr.data)
curr = curr.next
def print_linked_list_in_reverse(head, inputList=[]):
if head.next is None:
inputList.append(head.data)
return head.data == inputList[-1]
inputList.append(head.data)
if print_linked_list_in_reverse(head.next, inputList):
print(head.data)
print(inputList[-1])
return True
return False
def print_half_linked_list(head):
slow = head
fast = head
prevSlow = None
isOdd = False
while fast is not None and fast.next is not None:
prevSlow = slow
slow = slow.next
fast = fast.next.next
if fast is not None:
isOdd = True
slow = slow.next
while slow is not None:
print(slow.data)
slow = slow.next
headNode = Node(5)
headNode.next = Node(4)
headNode.next.next = Node(3)
headNode.next.next.next = Node(4)
headNode.next.next.next.next = Node(5)
# printNthFromLast(headNode, 2)
# print_linked_list(headNode)
# print(print_linked_list_in_reverse(headNode))
print_half_linked_list(headNode)