[算法题] Reverse Linked List

题目内容

题目来源:LeetCode

Reverse a singly linked list.

题目思路

这个属于经典问题,链表反转的思路基本上已经非常固定了。有两种非常常见的方法:1.三指针法 2.头插法


这个题目用到的是三指针法。

方法:设立三个指针,分别叫做pre, curr, next。这三个指针的功能分别是:现用next保存curr的下一个结点,免得以后找不到了。然后将curr指向pre,这一步实现了反转,然后让pre指向curr, curr指向next。

具体的解释这个博客写的非常明晰(也包括了头插法):http://blog.csdn.net/feliciafay/article/details/6841115

初始化的时候,pre=None,curr=pre.next , next=curr.next

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
        """
        pre=None
        next=None
        curr=head
        while curr:
            next=curr.next
            curr.next=pre
            pre=curr
            curr=next
        return pre       
原文地址:https://www.cnblogs.com/chengyuanqi/p/7161875.html