单链表的反转
1.非递归方式
cur指向当前结点,使用pre指向前一个结点,每次把cur->next指向pre即可
# -*- coding: utf-8 -*-
class LNode:
def __init__(self, elem, next_=None):
self.elem = elem
self.next_ = next_
class LList:
def __init__(self, _head=None):
self._head = _head
def no_recursive_reverse(self):
if self._head is None or self._head.next_ is None:
return self._head
pre = None
cur = self._head
h = cur
while cur:
h = cur
tmp = cur.next_
cur.next_ = pre
pre = cur
cur = tmp
return h
if __name__ == '__main__':
head = LNode(1)
p = head
for i in range(2, 10):
p.next_ = LNode(i)
p = p.next_
obj = LList(head)
q = obj.no_recursive_reverse()
while q:
print q.elem
q = q.next_
2.递归方式
# -*- coding: utf-8 -*-
class LNode:
def __init__(self, elem, next_=None):
self.elem = elem
self.next_ = next_
class LList:
def __init__(self, _head=None):
self._head = _head
@staticmethod
def recursive_reverse(old_head, new_head):
if old_head is None:
return
if old_head.next_ is None:
new_head = old_head
else:
new_head = LList.recursive_reverse(old_head.next_, new_head)
old_head.next_.next_ = old_head
old_head.next_ = None
return new_head
if __name__ == '__main__':
head = LNode(1)
p = head
for i in range(2, 10):
p.next_ = LNode(i)
p = p.next_
new_head_none = None
q = LList().recursive_reverse(head, new_head_none)
while q:
print q.elem
q = q.next_