题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
代码如下:
迭代:
class Solution(object):
def reverseList(self, head):
fir = head
sec = None
thi = None
while fir != None:
thi = fir.next
fir.next = sec
sec = fir
fir = thi
return sec
递归:
class Solution(object):
def reverseList(self, head):
if head.next == None:
return head
fir = self.reverseList(head.next)
head.next.next = head
head.next = None
return fir