-
Notifications
You must be signed in to change notification settings - Fork 0
/
Singly Linked List.py
66 lines (58 loc) · 1.61 KB
/
Singly Linked List.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 12:16:45 2020
@author: $parsh
"""
'''DS : Single linked list '''
class node:
# A wrapper Class
def __init__(self,data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def append(self,data):
new_node = node(data)
cur = self.head
while cur.next != None :
cur = cur.next
cur.next = new_node
def length(self):
cur = self.head
total = 0
while cur.next != None:
total+=1
cur = cur.next
return total
def display(self):
elems = []
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
elems.append(cur_node.data)
print(elems)
def get(self,index) :
if index>=self.length():
print ("ERROR : 'Get' Index out of range !")
return None
cur_idx = 0
cur_node = self.head
while True :
cur_node = cur_node.next
if cur_idx==index :
return cur_node.data
cur_idx+=1
def erase(self,index) :
if index>=self.length() :
print ("ERROR : 'Erase' Index out of range !")
return None
cur_idx = 0
cur_node = self.head
while True :
last_node = cur_node
cur_node = cur_node.next
if cur_idx == index :
last_node.next = cur_node.next
return
cur_idx += 1