本文适合有一定数据结构基础的人阅读(就是你要懂链表是什么)
在C/C++中,通常采用“指针+结构体”来实现链表;而在Python中,则可以采用“引用+类”来实现链表。
链表L中的每个元素都是一个对象,每个对象有一个关键字key和一个指针:next
题目:单链表倒序,并输出新的链表。
解题思路:
在C的时候我们使用三个指针遍历单链表,逐个链接点进行反转。python也可以采用类似的思路,其实语言并不是很大的关系。
代码(包含建立链表、添加节点、打印链表)
class Node:#定义节点
def __init__(self, initdata):
self.__data = initdata
self.__next = None
def getData(self):
return self.__data
def getNext(self):
return self.__next
def setData(self, newdata):
self.__data = newdata
def setNext(self, newnext):
self.__next = newnext
class SinCycLinkedlist:
def __init__(self):
self.head = Node(None)
self.head.setNext(self.head)
def add(self, item):
temp = Node(item)
temp.set