zoukankan      html  css  js  c++  java
  • 剑指offer15-反转链表

    题目描述

    输入一个链表,反转链表后,输出新链表的表头。

    示例

    输入  {1,2,3}

    返回值  {3,2,1}

    知识点回顾

     链表反转:递归法;迭代法

    代码

    #用递归的方式
    #
    -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here if pHead == None or pHead.next==None: return pHead newHead = self.ReverseList(pHead.next) //1->2->3->4->null:先反转pHead.next变为 1->(null<-2<-3<-4),此时1还是指向2 pHead.next.next=pHead //再将2指向原来的头指针1 pHead.next=None //将原来的头指针指向null return newHead // 返回新头指针
    #非递归的形式,一个个节点组装成新的反转链表
    #
    -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here if pHead == None or pHead.next == None: return pHead newHead=None //新节点初始化为NULL while pHead: tmp=pHead.next //临时节点存储pHead.next,否则直接下一个语句pHead.next=newHead会把原head.next的线断了,之后用pHead=pHead.next就不是原链表的下一个节点了 pHead.next=newHead //将当前头节点拆下来,指向新节点 newHead=pHead //将新链表的头指针移到最新拆解过来的节点 pHead=tmp //原头结点移到下一个,继续拆下一个节点到新链表 return newHead
  • 相关阅读:
    【转载】我的七个建议Joel Spolsky
    C语言文件读写操作
    【转】RO段、RW段和ZI段 Image$$??$$Limit 含义(zz)
    给大家一个测试webservice的软件
    .net 实现深拷贝的方法
    第一次设计数据访问层,大家给你建议,谢谢
    重新写博客
    (转)理解 Thread.Sleep 函数
    slk解压缩
    SMTP Service设置
  • 原文地址:https://www.cnblogs.com/foolangirl/p/14001710.html
Copyright © 2011-2022 走看看