class
node
:def
__init__
(self, value=
none
,next
=none):
self.value = value
self.
next
=next
class
linkedlist
:def
__init__
(self)
: self.head = node(
) self.tail =
none
self.length =
0def
peek
(self):if
not self.head.
next
:raise exception(
"linkedlist is empty"
)return self.head.
next
defget_first
(self)
:#得到鍊錶的第乙個元素
ifnot self.head.
next
:raise exception(
"linkedlist is empty"
)return self.head.
next
defget_last
(self)
:#得到鍊錶的最後乙個元素
ifnot self.head.
next
:raise exception(
"linkedlist is empty"
) node = self.head
while node.
next
!=none
: node = node.
next
return node
defget(self, index)
:#得到第index個元素,從0開始
if index <
0or index >= self.length:
raise exception(
"index is out of bound")if
not self.head.
next
:raise exception(
"linkedlist is empty"
) node = self.head.
next
for i in
range
(index)
: node = node.
next
return node
defadd_first
(self, value)
:#新增鍊錶第乙個元素
node = node(value,
none
) node.
next
= self.head.
next
self.head.
next
= node
self.length +=
1def
add_last
(self, value)
:#新增鍊錶最後乙個元素
new_node = node(value)
node = self.head
while node.
next
!=none
: node = node.
next
node.
next
= new_node
self.length +=
1def
add(self, index, value)
:#新增鍊錶中第index個元素
if index <
0or index > self.length:
raise exception(
"index is out of bound")if
not self.head.
next
:raise exception(
"linkedlist is empty"
) new_node = node(value)
node = self.head
for i in
range
(index)
: node = node.
next
new_node.
next
= node.
next
node.
next
= new_node
self.length +=
1def
remove_first
(self)
:#刪除鍊錶的第乙個元素
ifnot self.head.
next
:raise exception(
"linkedlist is empty"
) result = self.head.
next
self.head.
next
= self.head.
next
.next
self.length -=
1return result.value
defremove_last
(self)
:#刪除鍊錶的最後乙個元素
ifnot self.head.
next
:raise exception(
"linkedlist is empty"
) node = self.head.
next
prev = self.head
while node.
next
!=none
: prev = node
node = node.
next
prev.
next
=none
self.length -=
1return node.value
defremove
(self, index)
:#刪除鍊錶的第index個元素
if index <
0or index > self.length:
raise exception(
"index is out of bound")if
not self.head.
next
:raise exception(
"linkedlist is empty"
) node = self.head
for i in
range
(index)
: node = node.
next
result = node.
next
node.
next
= node.
next
.next
self.length -=
1return result.value
defprintlist
(self)
:#列印輸出鍊錶的元素
node = self.head.
next
while node:
print
(node.value, end=
" ")
node = node.
next
print(""
)
python鍊錶
class node def init self,data 要存的資料 self.data data 指向下乙個節點的指標 self.next none class linkedlist def init self 鍊錶長度 self.size 0 鍊錶的頭部 self.head none 鍊錶的尾...
python 鍊錶
在c c 中,通常採用 指標 結構體 來實現鍊錶 而在python中,則可以採用 引用 類 來實現鍊錶。節點類 class node def init self,data self.data data self.next none 鍊錶類 class linkedlist def init self...
python鍊錶 鍊錶重新排序
輸入 1 2 3 4 5 6 7 輸出 1 7 2 6 3 5 4 或者輸入 1 2 3 4 5 6 輸出 1 6 2 5 3 4 思路 1.將1 2 3 4 5 6 7分成 1 2 3 與 4 5 6 7,將後半部分逆序7 6 5 4 2.合併1 2 3與7 6 5 4 為1 7 2 6 3 5 ...