07-Python反转单链表

单链表的反转可以使用循环,也可以使用递归的方式

1.循环反转单链表

循环的方法中,使用pre指向前一个结点,cur指向当前结点,每次把cur->next指向pre即可。

image.png
class ListNode: 
  def __init__(self,x): 
    self.val=x; 
    self.next=None; 
 
def nonrecurse(head):       #循环的方法反转链表 
  if head is None or head.next is None: 
    return head; 
  pre=None; 
  cur=head; 
  h=head; 
  while cur: 
    h=cur; 
    tmp=cur.next; 
    cur.next=pre; 
    pre=cur; 
    cur=tmp; 
  return h; 
   
head=ListNode(1);  #测试代码 
p1=ListNode(2);   #建立链表1->2->3->4->None; 
p2=ListNode(3); 
p3=ListNode(4); 
head.next=p1; 
p1.next=p2; 
p2.next=p3; 
p=nonrecurse(head);  #输出链表 4->3->2->1->None 
while p: 
  print(p.val); 
  p=p.next; 

结果:

4
3
2
1

2.递归实现单链表反转

class ListNode: 
  def __init__(self,x): 
    self.val=x; 
    self.next=None; 
 
   
def recurse(head,newhead):  #递归,head为原链表的头结点,newhead为反转后链表的头结点 
  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; 
   
head=ListNode(1);        #测试代码 
p1=ListNode(2);         # 建立链表1->2->3->4->None 
p2=ListNode(3); 
p3=ListNode(4); 
head.next=p1; 
p1.next=p2; 
p2.next=p3; 
newhead=None; 
p=recurse(head,newhead);      #输出链表4->3->2->1->None 
while p: 
  print p.val; 
  p=p.next; 

运行结果:同上

4
3
2
1

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 搞懂单链表常见面试题 Hello 继上次的 搞懂基本排序算法,这个一星期,我总结了,我所学习和思考的单链表基础知识...
    醒着的码者阅读 10,051评论 1 45
  • 大学的时候不好好学习,老师在讲台上讲课,自己在以为老师看不到的座位看小说,现在用到了老师讲的知识,只能自己看书查资...
    和珏猫阅读 5,314评论 1 3
  • 链表删除[203] Remove Linked List Elements[19] Remove Nth Node...
    野狗子嗷嗷嗷阅读 11,422评论 4 35
  • 趣事忆童年,文友生共鸣。 幼时求学景,田埂露水情。 草结阴招用,厌学从此生。 留恋玩中趣,声声唤儿归。 ...
    鸣鸥阅读 1,865评论 5 4
  • 我是一个有价值的人 看到这个故事,让我看到了自己,对生活的抱怨,内心很愧疚,某个心里的障碍打开了,我希望能够记住这...
    唐汤圆阅读 1,761评论 0 0