编程实现单链表的逆转函数
实现单链表的逆转函数,输入一个链表,反转链表后,返回翻转之后的链表。
同从尾到头打印链表
# def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, head): if not head : return [] cur = head.next head.next = None #magic?#最后一个节点搞成空,不加死循环! while cur: nextNode = cur.next cur.next = head # head = cur cur = nextNode cur = head res = [] while cur: res.append(cur.val) cur = cur.next return res