在类中操作自身对象



我用Python为我的学生实现了一个链表,尤其是一个简单版本的"反向";方法

这是一个有效的版本:

class SimpleList:
def __init__(self, *args):
if len(args) == 0:
self.__cell = None
elif len(args) == 2:
if isinstance(args[1], SimpleList):
self.__cell = (args[0], args[1])
else:
print("Erreur 2")
else:
print("Erreur 3")
def car(self):
if not self.isNull():
return self.__cell[0]
print("Erreur 4")
def cdr(self):
if not self.isNull():
return self.__cell[1]
print("Erreur 5")
def isNull(self):
return self.__cell == None
def __repr__(self):
if self.isNull():
return '()'
else:
return '(' + repr(self.car()) + ',' + repr(self.cdr()) + ')'

def nbrElement(self):
num = 0
tab = self
while not(tab.isNull()):
num = num+1
tab = tab.cdr()
return num

def reverse(self):
num=self.nbrElement()-1
pCourant = SimpleList(self.car(),SimpleList())
tab = self.cdr()
for i in range(0,num-1):
tabTmp = tab
tab = tab.cdr()
tabTmp.__cell = (tabTmp.car(),pCourant)
pCourant= tabTmp
self.__cell = neww = (tab.car(),pCourant)

以及要执行的代码:

slA = SimpleList(10,SimpleList(9,SimpleList(8,SimpleList(7,SimpleList(6,SimpleList(5,SimpleList(4,SimpleList())))))))
print(slA)
slA.reverse()
print(slA)

但我需要重新定义新的尾部对象

我试着只用";交换;内部链接:

def reverse(self):
num=self.nbrElement()-1
pCourant = SimpleList()
tab = self
for i in range(0,num-1):
tabTmp = tab
tab = tab.cdr()
tabTmp.__cell = (tabTmp.car(),pCourant)
pCourant= tabTmp
self.__cell = neww = (tab.car(),pCourant)

有人能解释我这件事吗???感谢您的帮助


更新:

def reverse(self):
num=self.nbrElement()-1
pCourant = SimpleList()
tab = self
for i in range(0,num):
tabTmp = tab
tab = tab.cdr()
tabTmp.__cell = (tabTmp.car(),pCourant)
pCourant= tabTmp
neww = SimpleList(tab.car(),pCourant)
print(neww)
print(neww)
self.__cell = neww.__cell
slA = SimpleList(10,SimpleList(9,SimpleList(8,SimpleList())))
slA.reverse()
print(slA.cdr().cdr().car())
print(slA)

不是为了优化我的代码。。。但为了理解;内部逻辑";Python的

  • print(new)运行良好
  • 一个CCD_ 2做一个";最大递归深度">
  • 倒数第二个显示提供8,但通常显示10

感谢所有

由于我还在喝我的第一杯咖啡,这里有一个更简单的重新实现。

(__slots__是一个预优化;如果你愿意,你可以取消它。(

class ListCell:
__slots__ = ("value", "next")
def __init__(self, value, next=None):
self.value = value
self.next = next
def __repr__(self):
if not self.next:
return f"({self.value!r})"
else:
return f"({self.value!r},{self.next!r})"
def reverse(self):
prev = next = None
curr = self
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev  # Return new head
@classmethod
def from_iterable(cls, items):
head = tail = None
for item in items:
if head is None:
head = tail = cls(item)
else:
tail.next = cls(item)
tail = tail.next
return head

lc = ListCell.from_iterable([1, 2, 4, 8])
print(lc)
lc = lc.reverse()
print(lc)

这会打印出

(1,(2,(4,(8))))
(8,(4,(2,(1))))

最新更新