-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.py
125 lines (112 loc) · 2.59 KB
/
linkedlist.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# linkedlist.py
#
# Copyright 2016 Sajal Tyagi <[email protected]>
#
class LinkedList:
class Node:
def __init__(self,element,point):
self._ele = element
self._next = point
def __init__(self):
self._head = None
self._size = 0
def getData(self):
temp = self._head
if temp != None:
while temp._next != None :
print(temp._ele)
temp = temp._next
print(temp._ele)
def insertAtBegin(self,ele):
if self._head == None:
self._head = self.Node(ele, None)
else:
temp = self.Node(ele,self._head)
self._head = temp
self._size += 1
def insertAtLast(self,ele):
if self._head == None:
self._head = self.Node(ele, None)
else:
temp = self._head
while temp._next != None:
temp = temp._next
temp._next = self.Node(ele,None)
self._size += 1
def deleteAtLast(self):
ele = 0
if self._head == None:
print("Empty list")
elif self._head._next == None:
ele = self._head._ele
self._head = None
self._size -= 1
else:
temp = self._head
while temp._next._next != None:
temp = temp._next
ele = temp._next._ele
temp._next = None
self._size -= 1
return ele
def deleteAtBegin(self):
ele = 0
if self._head == None:
print("Empty list")
elif self._head._next == None:
ele = self._head._ele
self._head == None
self._size -= 1
else:
temp = self._head
ele = temp._ele
self._head = self._head._next
temp = None
self._size -= 1
return ele
def countNode(self):
return self._size
def insertAfterPosition(self,ele,pos=0):
if pos <= 0:
print("Invalid position item added at first.")
self.insertAtBegin(ele)
elif pos >= self._size:
print("Invalid position item added at last.")
self.insertAtLast(ele)
else:
temp = self._head
for i in range(0,pos - 1,1):
temp = temp._next
node = self.Node(ele,temp._next)
temp._next = node
self._size += 1
def insertBeforePosition(self,ele,pos=0):
if pos <= 0:
print("Invalid position item added at first.")
self.insertAtBegin(ele)
elif pos >= self._size:
print("Invalid position item added at last.")
self.insertAtLast(ele)
else:
temp = self._head
for i in range(0,pos - 2,1):
temp = temp._next
node = self.Node(ele,temp._next)
temp._next = node
self._size += 1
ll = LinkedList()
ll.insertAtBegin(23)
ll.insertAtBegin(54)
ll.insertAtLast(764)
ll.insertAtBegin(9284)
ll.insertAfterPosition(12,3)
ll.insertBeforePosition(98,3)
#ll.deleteAtLast()
#ll.deleteAtBegin()
#ll.deleteAtLast()
#ll.deleteAtLast()
ll.getData()
print(ll.countNode())