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

Solution+ rename + typo #34

Merged
merged 4 commits into from
Jan 16, 2020
Merged
Show file tree
Hide file tree
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
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