This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 789
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #34 from BZAghalarov/py
Solution+ rename + typo
- Loading branch information
Showing
4 changed files
with
467 additions
and
1 deletion.
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,69 @@ | ||
""" | ||
Leetcode : https://leetcode.com/problems/design-linked-list/ | ||
Geekforgeeks : https://www.educative.io/edpresso/how-to-create-a-linked-list-in-python | ||
This code passed all test cases in Leetcode on 10.01.2020: | ||
""" | ||
|
||
class ListNode: | ||
def __init__(self, val): | ||
self.val = val | ||
self.next = None | ||
|
||
|
||
class MyLinkedList(object): | ||
def __init__(self): | ||
self.head = None | ||
self.size = 0 | ||
|
||
def get(self, index): | ||
if index < 0 or index >= self.size: | ||
return -1 | ||
|
||
dummyHead = self.head | ||
for i in range(index): | ||
dummyHead = dummyHead.next | ||
return dummyHead.val | ||
|
||
def addAtHead(self, val): | ||
newNode = ListNode(val) | ||
newNode.next = self.head | ||
self.head = newNode | ||
self.size += 1 | ||
|
||
def addAtTail(self, val): | ||
newNode = ListNode(val) | ||
|
||
curr = self.head | ||
while curr.next: | ||
curr = curr.next | ||
curr.next = newNode | ||
self.size += 1 | ||
|
||
def addAtIndex(self, index, val): | ||
if index > self.size: | ||
return | ||
|
||
newNode = ListNode(val) | ||
curr = self.head | ||
if index <= 0: | ||
newNode.next = curr | ||
self.head = newNode | ||
else: | ||
for i in range(index - 1): | ||
curr = curr.next | ||
newNode.next = curr.next | ||
curr.next = newNode | ||
self.size += 1 | ||
|
||
def deleteAtIndex(self, index): | ||
if index < 0 or index >= self.size: | ||
return | ||
|
||
curr = self.head | ||
if index == 0: | ||
self.head = self.head.next | ||
else: | ||
for i in range(index - 1): | ||
curr = curr.next | ||
curr.next = curr.next.next | ||
self.size -= 1 |
Oops, something went wrong.