反转链表

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

输入: 1->2->3->4->5->NULL  输出: 5->4->3->2->1->NULL

 

双指针:定义两个指针,pre指向空,cur指向头节点,然后不断遍历cur,将 cur 的 next 指向 pre,然后 pre 和 cur 前进一位。

 

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre, cur = None,head
        while cur:
            tmp = cur.next
            cur.next = pre
            pre, cur = cur,tmp
        return pre

 

迭代法:终止条件是当前节点或者下一个节点==null 在函数内部,改变节点的指向,也就是 head 的下一个节点指向 head 递归函数那句

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # 递归终止条件是当前为空,或者下一个节点为空
        if(head==None or head.next==None):
            return head
        # 这里的cur就是最后一个节点
        cur = self.reverseList(head.next)
        # 这里请配合动画演示理解
        # 如果链表是 1->2->3->4->5,那么此时的cur就是5
        # 而head是4,head的下一个是5,下下一个是空
        # 所以head.next.next 就是5->4
        head.next.next = head
        # 防止链表循环,需要将head.next设置为空
        head.next = None
        # 每层递归函数都返回cur,也就是最后一个节点
        return cur

作者:wang_ni_ma
链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/dong-hua-yan-shi-duo-chong-jie-fa-206-fan-zhuan-li/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted @ 2020-08-28 09:47  ninian  阅读(65)  评论(0)    收藏  举报