-
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
Showing
2 changed files
with
54 additions
and
30 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
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 |
---|---|---|
@@ -1,38 +1,42 @@ | ||
""" | ||
Problem: | ||
Given a linked list, rearrange the node values such that they appear in alternating low -> high -> low -> high ... form. For example, given 1 -> 2 -> 3 -> 4 -> 5, you should return 1 -> 3 -> 2 -> 5 -> 4. | ||
Given a linked list, rearrange the node values such that they appear in alternating | ||
low -> high -> low -> high ... form. For example, given 1 -> 2 -> 3 -> 4 -> 5, you | ||
should return 1 -> 3 -> 2 -> 5 -> 4. | ||
""" | ||
|
||
from DataStructures.LinkedList import Node, Linked_list | ||
from DataStructures.LinkedList import Node, LinkedList | ||
|
||
|
||
def rearrange(self): | ||
# getting the nodes in sorted format | ||
nodes = [int(node) for node in self] | ||
def rearrange(ll: LinkedList) -> None: | ||
nodes_count = len(ll) | ||
nodes = [int(node) for node in ll] | ||
nodes.sort() | ||
# interleaving the nodes to form alternating pattern (low -> high -> low ...) | ||
for i in range(2, len(nodes), 2): | ||
|
||
for i in range(2, nodes_count, 2): | ||
nodes[i], nodes[i - 1] = nodes[i - 1], nodes[i] | ||
# updating the linked list | ||
curr = self.head | ||
for i in range(len(nodes)): | ||
|
||
curr = ll.head | ||
for i in range(nodes_count): | ||
curr.val = nodes[i] | ||
curr = curr.next | ||
|
||
|
||
# adding the rearrange method to the class | ||
setattr(Linked_list, "rearrange", rearrange) | ||
|
||
if __name__ == "__main__": | ||
LL = LinkedList() | ||
|
||
# DRIVER CODE | ||
LL = Linked_list() | ||
for i in range(1, 6): | ||
LL.add(i) | ||
|
||
for i in range(1, 6): | ||
LL.add(i) | ||
print(LL) | ||
rearrange(LL) | ||
print(LL) | ||
|
||
print(LL) | ||
|
||
LL.rearrange() | ||
""" | ||
SPECS: | ||
print(LL) | ||
TIME COMPLEXITY: O(n) | ||
SPACE COMPLEXITY: O(n) | ||
""" |