LeetCode初级算法--链表01:反转链表

LeetCode初级算法--链表01:反转链表

搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法、机器学习干货python

csdn:https://blog.csdn.net/baidu_31657889/git

csdn:https://blog.csdn.net/abcgkj/github

github:https://github.com/aimi-cn/AILearners面试

1、引子

这是由LeetCode官方推出的的经典面试题目清单~
这个模块对应的是探索的初级算法~旨在帮助入门算法。咱们第一遍刷的是leetcode推荐的题目。
查看完整的剑指Offer算法题解析请点击github连接:
github地址算法

2、题目

反转一个单链表。编程

示例:微信

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL复制代码

进阶:机器学习

你能够迭代或递归地反转链表。你可否用两种方法解决这道题?学习

一、思路

这个题对我来讲仍是有点难度了,其实原理不难,咱们咱们使用三个指针,分别指向当前遍历到的结点、它的前一个结点以及后一个结点。spa

在遍历的时候,作当前结点的尾结点和前一个结点的替换。

由于这个题目以前在刷LeetCode的时候已经作过详细的图解说明 你们看连接就能够:https://blog.csdn.net/baidu_31657889/article/details/91552141

二、编程实现

python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None or head.next==None:
            return head
        pre = None
        while head:
            next = head.next
            head.next = pre
            pre = head
            head = next
        return pre复制代码

AIMI-CN AI学习交流群【1015286623】 获取更多AI资料

分享技术,乐享生活:咱们的公众号计算机视觉这件小事每周推送“AI”系列资讯类文章,欢迎您的关注!

本文由博客一文多发平台 OpenWrite 发布!

相关文章
相关标签/搜索