Skip to content
This repository has been archived by the owner on Apr 29, 2024. It is now read-only.

Commit

Permalink
Merge pull request #34 from BZAghalarov/py
Browse files Browse the repository at this point in the history
Solution+ rename + typo
  • Loading branch information
bephrem1 authored Jan 16, 2020
2 parents 112bbaf + 4735cc1 commit ca2dd76
Show file tree
Hide file tree
Showing 4 changed files with 467 additions and 1 deletion.
69 changes: 69 additions & 0 deletions Linked Lists/DesingALinkedList/DesignALinkedList.py
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
Loading

0 comments on commit ca2dd76

Please sign in to comment.