LeetCode初級演算法--鏈表01:反轉鏈表
搜索微信公眾號:'AI-ming3526'或者'計算機視覺這件小事' 獲取更多演算法、機器學習干貨
csdn:https://blog.csdn.net/baidu_31657889/
csdn:https://blog.csdn.net/abcgkj/
github:https://github.com/aimi-cn/AILearners
一、引子
這是由LeetCode官方推出的的經典面試題目清單~
這個模塊對應的是探索的初級演算法~旨在幫助入門演算法,我們第一遍刷的是leetcode推薦的題目,
查看完整的劍指Offer演算法題決議請點擊github鏈接:
github地址
二、題目
反轉一個單鏈表,
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞回地反轉鏈表,你能否用兩種方法解決這道題?
1、思路
這個題對我來說還是有點難度了,其實原理不難,我們我們使用三個指標,分別指向當前遍歷到的結點、它的前一個結點以及后一個結點,
在遍歷的時候,做當前結點的尾結點和前一個結點的替換,
因為這個題目之前在刷LeetCode的時候已經做過詳細的圖解說明 大家看鏈接就可以:https://blog.csdn.net/baidu_31657889/article/details/91552141
2、編程實作
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 發布!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/67679.html
標籤:其他
