题目描述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
实现
思路如图示
- 用pre指针指向NULL,cur指针指向当前元素,不可用cur.next直接指向pre节点,这样失去与之后节点的联系。
- 所以再创建next指针指向cur.next元素
- 之后将cur.next指向pre节点,此时第一个节点的反转已完成,再将pre,cur指针向后移循环此步骤。
# 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, cur = None, head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list/