Python单链表逆置

来源:互联网 发布:pubmed数据库 编辑:程序博客网 时间:2024/05/20 20:47

1、循环反转单链表

# -*- coding:utf-8 -*-# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    def ReverseList(self, pHead):        if not pHead or not pHead.next:            return pHead                  last = None                  while pHead:            tmp = pHead.next            pHead.next = last            last = pHead            pHead = tmp        return last
2、递归反转单链表

# -*- coding:utf-8 -*-# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Nonedef ReverseList(self, pHead):      if head is None:           return;        if head.next is None:            newhead=head;        else :    newhead=recurse(head.next,newhead);  
          head.next.next=head;  
          head.next=None;        return newhead;  

原创粉丝点击