标签:lang 时间复杂度 init rev alt self efi reverse 示例
题目描述:
反转一个单链表。
涉及内容:链表
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路 :
提交结果:
完整代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
dummy=ListNode(0)
dummy.next=head
while head is not None and head.next is not None:
dnext=dummy.next
hnext=head.next
dummy.next=head.next
head.next=hnext.next
hnext.next=dnext
return dummy.next
**方法2 ** :
提交结果:
完整代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre=None
cur=head
while cur:
temp=cur.next
cur.next=pre
pre=cur
cur=temp
return pre
对比:
两种方法都是迭代法 时间复杂度是O(N) 空间复杂度为O(1)
标签:lang 时间复杂度 init rev alt self efi reverse 示例
原文地址:https://www.cnblogs.com/leohbz/p/14611503.html