程序员面试算法宝典-1.1 如何实现链表的逆序

题目描述:

给定一个带头结点的单链表,请将其逆序。即如果单链表原来为 head->1->2->3->4->5->6->7,那么逆序后变为head->7->6->5->4->3->2->1。

class LNode:
    def __init__(self):
        self.data = None # 数据域
        self.next = None # 指针域

 # 方法功能:对单链表进行逆序 输入参数:head:链表头结点
 # 方法一:就地逆序
def Reverse1(head):
    # 判断链表是否为空
    if head == None or head.next == None:
        return
    pre = None # 前驱结点
    cur = None # 当前结点
    next = None # 后继结点
    # 把链表首结点变为尾结点
    cur = head.next
    next = cur.next
    cur.next = None
    pre = cur
    cur = next
    # 使当前遍历到的节点cur指向其前驱结点
    while cur.next != None:
        next = cur.next
        cur.next = pre
        pre = cur
        cur = next
    # 链表最后一个节点指向倒数第二个节点
    cur.next = pre
    # 链表的头结点指向链表的尾结点
    head.next = cur

# 方法二:递归法
"""
方法功能:对不带头结点的单链表进行逆序
输入参数:firstRef:链表头结点
"""
def RecursiveReverse(head):
    # 如果链表为空或者链表中只有一个元素
    if head is None or head.next is None:
        return head
    else:
        # 反转后面的结点
        newhead = RecursiveReverse(head.next)
        # 把当前遍历的结点加到后面结点逆序后链表的尾部
        head.next.next = head
        head.next = None
    return newhead
"""
方法功能:对带头结点的单链表进行逆序
输入参数:head:链表头结点
"""
def Reverse2(head):
    if head is None:
        return
    # 获取链表的第一个结点
    firstNode = head.next
    # 对链表进行逆序
    newhead = RecursiveReverse(firstNode)
    # 头结点指向逆序后链表的第一个结点
    head.next = newhead
    return newhead

# 方法三:插入法
def Reverse3(head):
    # 判断链表是否为空
    if head is None or head.next is None:
        return
    cur = None # 当前结点
    next = None # 后继结点
    cur = head.next.next
    # 设置链表第一个结点为尾结点
    head.next.next = None
    # 把遍历到的节点插入到头结点的后面
    while cur is not None:
        next = cur.next
        
        cur.next = head.next
        head.next = cur
        cur = next


if __name__=="__main__":
    i = 1
    # 链表头结点
    head = LNode()
    cur = head
    while i<8:
        tmp = LNode() # 创建新的一个节点
        tmp.data = i  # 给节点数据域赋值
        cur.next = tmp # 头结点指向下一个节点
        cur = tmp # 指针移动
        i += 1
    print("逆序前:")
    cur = head.next # 获取头结点的下一个节点
    while cur != None:
        print(cur.data)
        cur = cur.next
    print("逆序后:")
    Reverse3(head)
    cur = head.next
    while cur != None:
        print(cur.data)
        cur = cur.next

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值