Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions data_structures/linked_list/rotate_to_the_right.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Node:
data: int
next_node: Node | None = None


def print_linked_list(head: Node | None) -> None:
"""
Print the entire linked list iteratively.

This function prints the elements of a linked list separated by '->'.

Parameters:
head (Node | None): The head of the linked list to be printed,
or None if the linked list is empty.

>>> head = insert_node(None, 0)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 1)
>>> print_linked_list(head)
0->2->1
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> print_linked_list(head)
0->2->1->4->5
"""
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = head.next_node
print(head.data)


def insert_node(head: Node | None, data: int) -> Node:
"""
Insert a new node at the end of a linked list and return the new head.

Parameters:
head (Node | None): The head of the linked list.
data (int): The data to be inserted into the new node.

Returns:
Node: The new head of the linked list.

>>> head = insert_node(None, 10)
>>> head = insert_node(head, 9)
>>> head = insert_node(head, 8)
>>> print_linked_list(head)
10->9->8
"""
new_node = Node(data)
# If the linked list is empty, the new_node becomes the head
if head is None:
return new_node

temp_node = head
while temp_node.next_node:
temp_node = temp_node.next_node

temp_node.next_node = new_node # type: ignore
return head


def rotate_to_the_right(head: Node, places: int) -> Node:
"""
Rotate a linked list to the right by places times.

Parameters:
head: The head of the linked list.
places: The number of places to rotate.

Returns:
Node: The head of the rotated linked list.

>>> rotate_to_the_right(None, places=1)
Traceback (most recent call last):
...
ValueError: The linked list is empty.
>>> head = insert_node(None, 1)
>>> rotate_to_the_right(head, places=1) == head
True
>>> head = insert_node(None, 1)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 3)
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> new_head = rotate_to_the_right(head, places=2)
>>> print_linked_list(new_head)
4->5->1->2->3
"""
# Check if the list is empty or has only one element
if not head:
raise ValueError("The linked list is empty.")

if head.next_node is None:
return head

# Calculate the length of the linked list
length = 1
temp_node = head
while temp_node.next_node is not None:
length += 1
temp_node = temp_node.next_node

# Adjust the value of places to avoid places longer than the list.
places %= length

if places == 0:
return head # As no rotation is needed.

# Find the new head position after rotation.
new_head_index = length - places

# Traverse to the new head position
temp_node = head
for _ in range(new_head_index - 1):
assert temp_node.next_node
temp_node = temp_node.next_node

# Update pointers to perform rotation
assert temp_node.next_node
new_head = temp_node.next_node
temp_node.next_node = None
temp_node = new_head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = head

assert new_head
return new_head

Comment thread
cclauss marked this conversation as resolved.

if __name__ == "__main__":
import doctest

doctest.testmod()
head = insert_node(None, 5)
head = insert_node(head, 1)
head = insert_node(head, 2)
head = insert_node(head, 4)
head = insert_node(head, 3)

print("Original list: ", end="")
print_linked_list(head)

places = 3
new_head = rotate_to_the_right(head, places)

print(f"After {places} iterations: ", end="")
print_linked_list(new_head)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
[NEW ALGORITHM] Rotate linked list by K. by Muhammadummerr · Pull Request #9278 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions data_structures/linked_list/rotate_to_the_right.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Node:
data: int
next_node: Node | None = None


def print_linked_list(head: Node | None) -> None:
"""
Print the entire linked list iteratively.

This function prints the elements of a linked list separated by '->'.

Parameters:
head (Node | None): The head of the linked list to be printed,
or None if the linked list is empty.

>>> head = insert_node(None, 0)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 1)
>>> print_linked_list(head)
0->2->1
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> print_linked_list(head)
0->2->1->4->5
"""
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = head.next_node
print(head.data)


def insert_node(head: Node | None, data: int) -> Node:
"""
Insert a new node at the end of a linked list and return the new head.

Parameters:
head (Node | None): The head of the linked list.
data (int): The data to be inserted into the new node.

Returns:
Node: The new head of the linked list.

>>> head = insert_node(None, 10)
>>> head = insert_node(head, 9)
>>> head = insert_node(head, 8)
>>> print_linked_list(head)
10->9->8
"""
new_node = Node(data)
# If the linked list is empty, the new_node becomes the head
if head is None:
return new_node

temp_node = head
while temp_node.next_node:
temp_node = temp_node.next_node

temp_node.next_node = new_node # type: ignore
return head


def rotate_to_the_right(head: Node, places: int) -> Node:
"""
Rotate a linked list to the right by places times.

Parameters:
head: The head of the linked list.
places: The number of places to rotate.

Returns:
Node: The head of the rotated linked list.

>>> rotate_to_the_right(None, places=1)
Traceback (most recent call last):
...
ValueError: The linked list is empty.
>>> head = insert_node(None, 1)
>>> rotate_to_the_right(head, places=1) == head
True
>>> head = insert_node(None, 1)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 3)
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> new_head = rotate_to_the_right(head, places=2)
>>> print_linked_list(new_head)
4->5->1->2->3
"""
# Check if the list is empty or has only one element
if not head:
raise ValueError("The linked list is empty.")

if head.next_node is None:
return head

# Calculate the length of the linked list
length = 1
temp_node = head
while temp_node.next_node is not None:
length += 1
temp_node = temp_node.next_node

# Adjust the value of places to avoid places longer than the list.
places %= length

if places == 0:
return head # As no rotation is needed.

# Find the new head position after rotation.
new_head_index = length - places

# Traverse to the new head position
temp_node = head
for _ in range(new_head_index - 1):
assert temp_node.next_node
temp_node = temp_node.next_node

# Update pointers to perform rotation
assert temp_node.next_node
new_head = temp_node.next_node
temp_node.next_node = None
temp_node = new_head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = head

assert new_head
return new_head

Comment thread
cclauss marked this conversation as resolved.

if __name__ == "__main__":
import doctest

doctest.testmod()
head = insert_node(None, 5)
head = insert_node(head, 1)
head = insert_node(head, 2)
head = insert_node(head, 4)
head = insert_node(head, 3)

print("Original list: ", end="")
print_linked_list(head)

places = 3
new_head = rotate_to_the_right(head, places)

print(f"After {places} iterations: ", end="")
print_linked_list(new_head)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [NEW ALGORITHM] Rotate linked list by K. by Muhammadummerr · Pull Request #9278 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions data_structures/linked_list/rotate_to_the_right.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Node:
data: int
next_node: Node | None = None


def print_linked_list(head: Node | None) -> None:
"""
Print the entire linked list iteratively.

This function prints the elements of a linked list separated by '->'.

Parameters:
head (Node | None): The head of the linked list to be printed,
or None if the linked list is empty.

>>> head = insert_node(None, 0)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 1)
>>> print_linked_list(head)
0->2->1
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> print_linked_list(head)
0->2->1->4->5
"""
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = head.next_node
print(head.data)


def insert_node(head: Node | None, data: int) -> Node:
"""
Insert a new node at the end of a linked list and return the new head.

Parameters:
head (Node | None): The head of the linked list.
data (int): The data to be inserted into the new node.

Returns:
Node: The new head of the linked list.

>>> head = insert_node(None, 10)
>>> head = insert_node(head, 9)
>>> head = insert_node(head, 8)
>>> print_linked_list(head)
10->9->8
"""
new_node = Node(data)
# If the linked list is empty, the new_node becomes the head
if head is None:
return new_node

temp_node = head
while temp_node.next_node:
temp_node = temp_node.next_node

temp_node.next_node = new_node # type: ignore
return head


def rotate_to_the_right(head: Node, places: int) -> Node:
"""
Rotate a linked list to the right by places times.

Parameters:
head: The head of the linked list.
places: The number of places to rotate.

Returns:
Node: The head of the rotated linked list.

>>> rotate_to_the_right(None, places=1)
Traceback (most recent call last):
...
ValueError: The linked list is empty.
>>> head = insert_node(None, 1)
>>> rotate_to_the_right(head, places=1) == head
True
>>> head = insert_node(None, 1)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 3)
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> new_head = rotate_to_the_right(head, places=2)
>>> print_linked_list(new_head)
4->5->1->2->3
"""
# Check if the list is empty or has only one element
if not head:
raise ValueError("The linked list is empty.")

if head.next_node is None:
return head

# Calculate the length of the linked list
length = 1
temp_node = head
while temp_node.next_node is not None:
length += 1
temp_node = temp_node.next_node

# Adjust the value of places to avoid places longer than the list.
places %= length

if places == 0:
return head # As no rotation is needed.

# Find the new head position after rotation.
new_head_index = length - places

# Traverse to the new head position
temp_node = head
for _ in range(new_head_index - 1):
assert temp_node.next_node
temp_node = temp_node.next_node

# Update pointers to perform rotation
assert temp_node.next_node
new_head = temp_node.next_node
temp_node.next_node = None
temp_node = new_head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = head

assert new_head
return new_head

Comment thread
cclauss marked this conversation as resolved.

if __name__ == "__main__":
import doctest

doctest.testmod()
head = insert_node(None, 5)
head = insert_node(head, 1)
head = insert_node(head, 2)
head = insert_node(head, 4)
head = insert_node(head, 3)

print("Original list: ", end="")
print_linked_list(head)

places = 3
new_head = rotate_to_the_right(head, places)

print(f"After {places} iterations: ", end="")
print_linked_list(new_head)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [NEW ALGORITHM] Rotate linked list by K. by Muhammadummerr · Pull Request #9278 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions data_structures/linked_list/rotate_to_the_right.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Node:
data: int
next_node: Node | None = None


def print_linked_list(head: Node | None) -> None:
"""
Print the entire linked list iteratively.

This function prints the elements of a linked list separated by '->'.

Parameters:
head (Node | None): The head of the linked list to be printed,
or None if the linked list is empty.

>>> head = insert_node(None, 0)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 1)
>>> print_linked_list(head)
0->2->1
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> print_linked_list(head)
0->2->1->4->5
"""
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = head.next_node
print(head.data)


def insert_node(head: Node | None, data: int) -> Node:
"""
Insert a new node at the end of a linked list and return the new head.

Parameters:
head (Node | None): The head of the linked list.
data (int): The data to be inserted into the new node.

Returns:
Node: The new head of the linked list.

>>> head = insert_node(None, 10)
>>> head = insert_node(head, 9)
>>> head = insert_node(head, 8)
>>> print_linked_list(head)
10->9->8
"""
new_node = Node(data)
# If the linked list is empty, the new_node becomes the head
if head is None:
return new_node

temp_node = head
while temp_node.next_node:
temp_node = temp_node.next_node

temp_node.next_node = new_node # type: ignore
return head


def rotate_to_the_right(head: Node, places: int) -> Node:
"""
Rotate a linked list to the right by places times.

Parameters:
head: The head of the linked list.
places: The number of places to rotate.

Returns:
Node: The head of the rotated linked list.

>>> rotate_to_the_right(None, places=1)
Traceback (most recent call last):
...
ValueError: The linked list is empty.
>>> head = insert_node(None, 1)
>>> rotate_to_the_right(head, places=1) == head
True
>>> head = insert_node(None, 1)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 3)
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> new_head = rotate_to_the_right(head, places=2)
>>> print_linked_list(new_head)
4->5->1->2->3
"""
# Check if the list is empty or has only one element
if not head:
raise ValueError("The linked list is empty.")

if head.next_node is None:
return head

# Calculate the length of the linked list
length = 1
temp_node = head
while temp_node.next_node is not None:
length += 1
temp_node = temp_node.next_node

# Adjust the value of places to avoid places longer than the list.
places %= length

if places == 0:
return head # As no rotation is needed.

# Find the new head position after rotation.
new_head_index = length - places

# Traverse to the new head position
temp_node = head
for _ in range(new_head_index - 1):
assert temp_node.next_node
temp_node = temp_node.next_node

# Update pointers to perform rotation
assert temp_node.next_node
new_head = temp_node.next_node
temp_node.next_node = None
temp_node = new_head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = head

assert new_head
return new_head

Comment thread
cclauss marked this conversation as resolved.

if __name__ == "__main__":
import doctest

doctest.testmod()
head = insert_node(None, 5)
head = insert_node(head, 1)
head = insert_node(head, 2)
head = insert_node(head, 4)
head = insert_node(head, 3)

print("Original list: ", end="")
print_linked_list(head)

places = 3
new_head = rotate_to_the_right(head, places)

print(f"After {places} iterations: ", end="")
print_linked_list(new_head)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' [NEW ALGORITHM] Rotate linked list by K. by Muhammadummerr · Pull Request #9278 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions data_structures/linked_list/rotate_to_the_right.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Node:
data: int
next_node: Node | None = None


def print_linked_list(head: Node | None) -> None:
"""
Print the entire linked list iteratively.

This function prints the elements of a linked list separated by '->'.

Parameters:
head (Node | None): The head of the linked list to be printed,
or None if the linked list is empty.

>>> head = insert_node(None, 0)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 1)
>>> print_linked_list(head)
0->2->1
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> print_linked_list(head)
0->2->1->4->5
"""
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = head.next_node
print(head.data)


def insert_node(head: Node | None, data: int) -> Node:
"""
Insert a new node at the end of a linked list and return the new head.

Parameters:
head (Node | None): The head of the linked list.
data (int): The data to be inserted into the new node.

Returns:
Node: The new head of the linked list.

>>> head = insert_node(None, 10)
>>> head = insert_node(head, 9)
>>> head = insert_node(head, 8)
>>> print_linked_list(head)
10->9->8
"""
new_node = Node(data)
# If the linked list is empty, the new_node becomes the head
if head is None:
return new_node

temp_node = head
while temp_node.next_node:
temp_node = temp_node.next_node

temp_node.next_node = new_node # type: ignore
return head


def rotate_to_the_right(head: Node, places: int) -> Node:
"""
Rotate a linked list to the right by places times.

Parameters:
head: The head of the linked list.
places: The number of places to rotate.

Returns:
Node: The head of the rotated linked list.

>>> rotate_to_the_right(None, places=1)
Traceback (most recent call last):
...
ValueError: The linked list is empty.
>>> head = insert_node(None, 1)
>>> rotate_to_the_right(head, places=1) == head
True
>>> head = insert_node(None, 1)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 3)
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> new_head = rotate_to_the_right(head, places=2)
>>> print_linked_list(new_head)
4->5->1->2->3
"""
# Check if the list is empty or has only one element
if not head:
raise ValueError("The linked list is empty.")

if head.next_node is None:
return head

# Calculate the length of the linked list
length = 1
temp_node = head
while temp_node.next_node is not None:
length += 1
temp_node = temp_node.next_node

# Adjust the value of places to avoid places longer than the list.
places %= length

if places == 0:
return head # As no rotation is needed.

# Find the new head position after rotation.
new_head_index = length - places

# Traverse to the new head position
temp_node = head
for _ in range(new_head_index - 1):
assert temp_node.next_node
temp_node = temp_node.next_node

# Update pointers to perform rotation
assert temp_node.next_node
new_head = temp_node.next_node
temp_node.next_node = None
temp_node = new_head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = head

assert new_head
return new_head

Comment thread
cclauss marked this conversation as resolved.

if __name__ == "__main__":
import doctest

doctest.testmod()
head = insert_node(None, 5)
head = insert_node(head, 1)
head = insert_node(head, 2)
head = insert_node(head, 4)
head = insert_node(head, 3)

print("Original list: ", end="")
print_linked_list(head)

places = 3
new_head = rotate_to_the_right(head, places)

print(f"After {places} iterations: ", end="")
print_linked_list(new_head)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [NEW ALGORITHM] Rotate linked list by K. by Muhammadummerr · Pull Request #9278 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions data_structures/linked_list/rotate_to_the_right.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Node:
data: int
next_node: Node | None = None


def print_linked_list(head: Node | None) -> None:
"""
Print the entire linked list iteratively.

This function prints the elements of a linked list separated by '->'.

Parameters:
head (Node | None): The head of the linked list to be printed,
or None if the linked list is empty.

>>> head = insert_node(None, 0)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 1)
>>> print_linked_list(head)
0->2->1
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> print_linked_list(head)
0->2->1->4->5
"""
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = head.next_node
print(head.data)


def insert_node(head: Node | None, data: int) -> Node:
"""
Insert a new node at the end of a linked list and return the new head.

Parameters:
head (Node | None): The head of the linked list.
data (int): The data to be inserted into the new node.

Returns:
Node: The new head of the linked list.

>>> head = insert_node(None, 10)
>>> head = insert_node(head, 9)
>>> head = insert_node(head, 8)
>>> print_linked_list(head)
10->9->8
"""
new_node = Node(data)
# If the linked list is empty, the new_node becomes the head
if head is None:
return new_node

temp_node = head
while temp_node.next_node:
temp_node = temp_node.next_node

temp_node.next_node = new_node # type: ignore
return head


def rotate_to_the_right(head: Node, places: int) -> Node:
"""
Rotate a linked list to the right by places times.

Parameters:
head: The head of the linked list.
places: The number of places to rotate.

Returns:
Node: The head of the rotated linked list.

>>> rotate_to_the_right(None, places=1)
Traceback (most recent call last):
...
ValueError: The linked list is empty.
>>> head = insert_node(None, 1)
>>> rotate_to_the_right(head, places=1) == head
True
>>> head = insert_node(None, 1)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 3)
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> new_head = rotate_to_the_right(head, places=2)
>>> print_linked_list(new_head)
4->5->1->2->3
"""
# Check if the list is empty or has only one element
if not head:
raise ValueError("The linked list is empty.")

if head.next_node is None:
return head

# Calculate the length of the linked list
length = 1
temp_node = head
while temp_node.next_node is not None:
length += 1
temp_node = temp_node.next_node

# Adjust the value of places to avoid places longer than the list.
places %= length

if places == 0:
return head # As no rotation is needed.

# Find the new head position after rotation.
new_head_index = length - places

# Traverse to the new head position
temp_node = head
for _ in range(new_head_index - 1):
assert temp_node.next_node
temp_node = temp_node.next_node

# Update pointers to perform rotation
assert temp_node.next_node
new_head = temp_node.next_node
temp_node.next_node = None
temp_node = new_head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = head

assert new_head
return new_head

Comment thread
cclauss marked this conversation as resolved.

if __name__ == "__main__":
import doctest

doctest.testmod()
head = insert_node(None, 5)
head = insert_node(head, 1)
head = insert_node(head, 2)
head = insert_node(head, 4)
head = insert_node(head, 3)

print("Original list: ", end="")
print_linked_list(head)

places = 3
new_head = rotate_to_the_right(head, places)

print(f"After {places} iterations: ", end="")
print_linked_list(new_head)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); [NEW ALGORITHM] Rotate linked list by K. by Muhammadummerr · Pull Request #9278 · TheAlgorithms/Python · GitHub
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions data_structures/linked_list/rotate_to_the_right.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Node:
data: int
next_node: Node | None = None


def print_linked_list(head: Node | None) -> None:
"""
Print the entire linked list iteratively.

This function prints the elements of a linked list separated by '->'.

Parameters:
head (Node | None): The head of the linked list to be printed,
or None if the linked list is empty.

>>> head = insert_node(None, 0)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 1)
>>> print_linked_list(head)
0->2->1
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> print_linked_list(head)
0->2->1->4->5
"""
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = head.next_node
print(head.data)


def insert_node(head: Node | None, data: int) -> Node:
"""
Insert a new node at the end of a linked list and return the new head.

Parameters:
head (Node | None): The head of the linked list.
data (int): The data to be inserted into the new node.

Returns:
Node: The new head of the linked list.

>>> head = insert_node(None, 10)
>>> head = insert_node(head, 9)
>>> head = insert_node(head, 8)
>>> print_linked_list(head)
10->9->8
"""
new_node = Node(data)
# If the linked list is empty, the new_node becomes the head
if head is None:
return new_node

temp_node = head
while temp_node.next_node:
temp_node = temp_node.next_node

temp_node.next_node = new_node # type: ignore
return head


def rotate_to_the_right(head: Node, places: int) -> Node:
"""
Rotate a linked list to the right by places times.

Parameters:
head: The head of the linked list.
places: The number of places to rotate.

Returns:
Node: The head of the rotated linked list.

>>> rotate_to_the_right(None, places=1)
Traceback (most recent call last):
...
ValueError: The linked list is empty.
>>> head = insert_node(None, 1)
>>> rotate_to_the_right(head, places=1) == head
True
>>> head = insert_node(None, 1)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 3)
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> new_head = rotate_to_the_right(head, places=2)
>>> print_linked_list(new_head)
4->5->1->2->3
"""
# Check if the list is empty or has only one element
if not head:
raise ValueError("The linked list is empty.")

if head.next_node is None:
return head

# Calculate the length of the linked list
length = 1
temp_node = head
while temp_node.next_node is not None:
length += 1
temp_node = temp_node.next_node

# Adjust the value of places to avoid places longer than the list.
places %= length

if places == 0:
return head # As no rotation is needed.

# Find the new head position after rotation.
new_head_index = length - places

# Traverse to the new head position
temp_node = head
for _ in range(new_head_index - 1):
assert temp_node.next_node
temp_node = temp_node.next_node

# Update pointers to perform rotation
assert temp_node.next_node
new_head = temp_node.next_node
temp_node.next_node = None
temp_node = new_head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = head

assert new_head
return new_head

Comment thread
cclauss marked this conversation as resolved.

if __name__ == "__main__":
import doctest

doctest.testmod()
head = insert_node(None, 5)
head = insert_node(head, 1)
head = insert_node(head, 2)
head = insert_node(head, 4)
head = insert_node(head, 3)

print("Original list: ", end="")
print_linked_list(head)

places = 3
new_head = rotate_to_the_right(head, places)

print(f"After {places} iterations: ", end="")
print_linked_list(new_head)