定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
来源:力扣(LeetCode)
初版代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return None
cur = head.next
first_loop = True
while cur:
next = cur.next
cur.next = head
if first_loop:
head.next = None
first_loop = False
head = cur
cur = next
return head
改进后的:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
while head:
next = head.next
head.next = pre
pre = head
head = next
return pre
昨天面试sidechef遇到的原题,写了个复杂度O(n^2)的算法…
一遍遍历即可,关键就是保存next信息,这样修改完next后不至于断链。