-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhomework1-2.py
More file actions
111 lines (95 loc) · 2.65 KB
/
homework1-2.py
File metadata and controls
111 lines (95 loc) · 2.65 KB
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
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 5 15:16:45 2019
@author: 10539
"""
class Node(object):
def __init__(self,item):
self.elem = item
self.prev = None
self.next = None
class DoubleLinkList(object):
def __init__(self,node=None):
self.__head = node
def is_empty(self):
return self.__head == None
def length(self):
cur = self.__head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
cur = self.__head
while cur != None:
print(cur.elem,end=" ")
cur = cur.next
print("")
def add(self,item):
node = Node(item)
cur = self.__head
node.next = cur
self.__head = node
def append(self,item):
node = Node(item)
cur = self.__head
prev = None
if cur == None:
self.add(item)
else:
while cur != None:
if cur.next == None:
cur.next = node
node.prev = cur
node.next = None
break
else:
prev = cur
cur = cur.next
def insert(self,pos, item):
node = Node(item)
cur = self.__head
prev = None
count = 0
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
while count < pos:
if (count+1) == pos:
prev.next = node
node.next = cur
break
else:
prev = cur
cur = cur.next
count += 1
def remove(self,item):
cur = self.__head
prev = None
while cur != None:
if cur.elem == item:
if cur == self.__head:
self.__head = cur.next
else:
prev.next = cur.next
cur.prev = prev
break
else:
prev = cur
cur = cur.next
def index(self,pos):
cur = self.__head
count = 0
if pos <= 0 or pos > self.length():
return False
else:
while count < pos:
if (count+1) == pos:
return cur.elem
break
else:
cur = cur.next
count += 1