LeetCode 206题 反转链表 (21.4.2)
作者:互联网
LeetCode 206题 反转链表
题目描述:
反转一个单链表。
涉及内容:链表
示例:
输入: 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)
标签:21.4,head,ListNode,cur,val,self,next,链表,LeetCode 来源: https://www.cnblogs.com/leohbz/p/14611503.html