反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路1:
扫描一遍链表,创建栈保存元素。重建链表,出栈为节点值。
代码1:
# 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
res=[]
while head:
res.append(head.val)
head=head.next
m=ListNode(res.pop())
n=m
while res:
m.next=ListNode(res.pop())
m=m.next
return n
分析:
时间复杂度O(N),空间复杂度O(N)
此代码击败68%Python提交。
思路2:
temp思想。扫描时进行复制,可同时避免空链表的问题。
# 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
"""
cur=None
pre=None
while head:
cur=head
head=head.next
cur.next=pre
pre=cur
return cur
分析:
此解法为Python最佳。