Skip to content

Commit

Permalink
added linked lists
Browse files Browse the repository at this point in the history
  • Loading branch information
Pizhlo committed May 10, 2024
1 parent 1709044 commit 1fa227e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 11 deletions.
26 changes: 26 additions & 0 deletions leetcode/linked_list_cycle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Given head, the head of a linked list, determine if the linked list has a cycle in it.

# There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer.
# Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

# Return true if there is a cycle in the linked list. Otherwise, return false.

# https://leetcode.com/problems/linked-list-cycle/description/

from typing import Optional

class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
fast = slow = head

while fast and fast.next:
slow, fast = slow.next, fast.next.next
if fast == slow:
return True

return False
43 changes: 32 additions & 11 deletions stepik/linked_list/linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,47 @@ def __init__(self):
self.top = Node()
self.tail = None

def append_to_start(self, value):
"""
Добавление нового элемента в начало связного списка.
Время работы O(1).
"""

new_node = Node(value)
new_node.next_node = self.top.next_node
self.top.next_node = new_node
if self.tail is None:
self.tail = new_node

def append_to_end(self, value):
"""
Добавление нового элемента в конец связного списка.
Время работы O(1).
"""

tail = self.tail
if tail is None:
tail = Node()

tail.next_node = Node(value)
new_node = Node(value)

def append_to_start(self, value):
if self.tail is not None:
self.tail.next_node = new_node
self.tail = new_node
return

self.top.next_node = new_node
self.tail = new_node

def append_after_target(self, target, value):
"""
Добавление нового элемента в начало связного списка.
Время работы O(1).
Добавление элемента после некоторого значения.
"""

node = Node(value=value, next_node=self.top.next_node)
self.top.next_node = node
current = self.top.next_node
node = Node(value)

while current is not None:
if current.value == target:
node.next_node = current.next_node
current.next_node = node
current = current.next_node

def delete(self, value):
"""
Expand Down Expand Up @@ -71,5 +92,5 @@ def __str__(self):
l.append_to_start(1)
l.append_to_end(2)
l.append_to_end(3)

l.append_after_target(1, 4)
print(l)

0 comments on commit 1fa227e

Please sign in to comment.