如果加结点是加在结尾的,
有两种inverse方法,第一种比较笨的是在创建一个新的链表,遍历原来的链表,把结点以加到开头的方式加到新链表,返回新链表,时间复杂度O(n),空间复杂度O(n)。第二种,推荐用法,原地置换,首先初始化prev为空,next为空, cur为头结点,循环当cur不为空,保存cur的下一个结点为next,改变cur的下一个结点为prev,prev和cur向前一步,循环直到cur为空,最后令prev为头结点,完毕。
class Node():
def __init__(self, val, next=None):
self.val = val
self.next = next
class LinkedList():
def __init__(self):
self.head = None
def AtEnd(self, val):
newNode = Node(val)
if not self.head:
self.head = newNode
return
tmp = self.head
while tmp.next:
tmp = tmp.next
tmp.next = newNode
def AtBegin(self, val):
print("inside at begin:{}".format(val))
newNode = Node(val)
if not self.head: # 如果头结点为空,令头结点为新结点
self.head = newNode
return
tmp = self.head # 取头结点
newNode.next = tmp # 令新结点的下一位为头结点
self.head = newNode # 令头结点为新结点
def inverse(self):
inverseLinked_List = LinkedList()
tmp = self.head
while tmp:
inverseLinked_List.AtBegin(tmp.val)
tmp = tmp.next
return inverseLinked_List
def quick_inverse(self):
next = None
prev = None
cur = self.head
while cur is not None:
next = cur.next # save next node
cur.next = prev # change next of cur
prev = cur
cur = next # move prev and cur one step forward
self.head = prev # set prev as head
def print(self):
tmp = self.head
while tmp:
print(tmp.val)
tmp = tmp.next
L = LinkedList()
L.AtEnd(1)
L.AtEnd(2)
L.AtEnd(3)
# L.print()
# inverted = L.inverse()
# inverted.print()
L.quick_inverse()
L.print()