Reverse a linked list.
Example
Example1:
For linked list 1->2->3, the reversed linked list is 3->2->1
Example2:
For linked list 1->2->3->4, the reversed linked list is 4->3->2->1
Challenge
Reverse it in-place and in one-pass
# 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 is None:
return None
before = None
pos = head
while(pos.next):
after = pos.next
pos.next = before
before = pos
pos = after
pos.next = before
return pos
重点是Reverse it in-place and in one-pass。
处理好pos,before,after的关系,理顺
注意:
[Lintcode]35. Reverse Linked List/[Leetcode]206. Reverse Linked List
原文:https://www.cnblogs.com/siriusli/p/10365209.html