Skip to content

Instantly share code, notes, and snippets.

@pipethedev
Last active May 10, 2020 22:25
Show Gist options
  • Select an option

  • Save pipethedev/dbe85fcf4bf33caf245a66b92a274732 to your computer and use it in GitHub Desktop.

Select an option

Save pipethedev/dbe85fcf4bf33caf245a66b92a274732 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
class Node:
def __init__(self, forward=None):
self.data = data
self.forward = forward
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def insertFirst(self, data):
self.head = Node(data, self.head)
self.size += 1
def insertAt(self, index):
if index > 0 and index > self.size:
return
if index == 0:
self.insertFirst(data)
node = Node(data)
current = self.head
count = 0
while count < index:
previous = current
count += 1
current = current.forward
node.forward = current
previous.forward = node
self.size += 1
def removeAt(self, index):
if index > 0 and index > self.size:
return
current = self.head
previous
count = 0
if index == 0:
self.head = current.forward
else:
while count < index:
count += 1
previous = current
current = current.forward
previous.forward = current.forward
self.size -= 1
def insertLast(self, data):
node = Node(data)
if self.head is not None:
self.head = node
else:
current = self.head
count = 0
while current.forward:
current = current.forward
current.forward = node
self.size += 1
def getAt(self, index):
current = self.head
count = 0
while current:
if count == index:
print (current.data)
count += 1
current = current.forward
return None
def clearList(self):
self.head = null
self.size = 0
def printListData(self):
current = self.head
while current:
print (current.data)
current = current.forward
ll = LinkedList()
ll.insertFirst(100)
ll.insertAt(2)
ll.getAt(2)
#ll.removeAt()
#ll.clearList()
ll.printListData()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment