1.題目
(1)Create class Linked List (Unordered)
(2)Create class Linked List (ordered)
List of operations a link list should supported:
1.Initialize (empty/from list)
2.isEmpty
3.add(val)
4.remove(val)
5.__ str __
6.__ repr __
7.index
8.__ contains __
9.insert(idx, val)
10.len
(Code to be completed in class)
2.解題思路
先實現簡單的function,再研究較難的function。
function實現順序:
Initialize -> __ str __ -> __ repr __ -> isEmpty -> index -> __ contains __ -> len -> add -> remove(較難) -> insert (較難)
對於有序鏈表,需要修改函數 add() 和 insert()。
3.code:
(1)創建結點
#define Node
class Node():
def __init__(self, val, nxt):
self.val = val
self.next = nxt
def __str__(self):
return str(self.val)
def __repr__(self):
return 'Node(' + str(self.val) + ')'
(2)創建class LinkedList
class LinkedList():
def __init__(self, lst = None):
self.head = None
if lst != None:
for val in lst:
self.add(val)
def add(self, val):
self.head = Node(val, self.head)
def remove(self, val):
p = self.head
# if list is None, do nothing
if p == None:
return
# if the first val need to remove
if p.val == val:
self.head = p.next
while p.next != None and p.next.val != val:
p = p.next
if p.next != None:
p.next = p.next.next
# if the val is not included in the list,do nothing
def index(self, val):
p = self.head
idx = 0
while p != None:
if p.val == val:
return idx
idx += 1
p = p.next
return -1 # not find
def insert(self, idx, val):
# idx = 0 or list is empty
if idx == 0 or self.head == None:
self.add(val)
# if idx is larger than length,insert at the end of the list
elif idx > len(self):
p = self.head
while p != None:
p = p.next
p.next = Node(val, None)
else:
p = self.head
while p != None and idx > 1:
p = p.next
idx -= 1
p.next = Node(val, p.next)
def isEmpty(self):
return self.head == None
def __contains__(self, val):
return self.index(val) != -1
def __len__(self):
p = self.head
l = 0
while p != None:
l += 1
p = p.next
return l
def __str__(self):
p = self.head
s = '->'
while p != None:
s += str(p.val) + '->'
p = p.next
s += 'None'
return s
def __repr__(self):
return 'LinkedList(' + str(self) + ')'
(3)創建 class OrderedLinkedList
class OrderedLinkedList(LinkedList):
def add(self, val):
p = self.head
if not p:
self.head = Node(val, None)
elif val < p.val:
self.head = Node(val, p)
else:
while p != None and p.next.val < val:
p = p.next
p.next = Node(val, p.next)
def insert(self, idx, val):
#ignore idx
self.add(val)
測試代碼
ol = OrderedLinkedList([5,3,1,4])
print(ol)
ol.add(2)
print(ol)
ol.remove(3)
print(ol)
結果
->1->3->4->5->None
->1->2->3->4->5->None
->1->2->4->5->None