美文网首页
8.【链表】反转链表

8.【链表】反转链表

作者: blackzero2193 | 来源:发表于2019-11-11 21:46 被阅读0次

题目链接:https://leetcode-cn.com/problems/reverse-linked-list/
描述:反转一个单链表。

示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

代码

# 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
        cur = head
        p = head.next
        pre = None
        while p:
            cur.next = pre
            pre = cur
            cur = p
            p = p.next
        cur.next = pre
        return cur

相关文章

网友评论

      本文标题:8.【链表】反转链表

      本文链接:https://www.haomeiwen.com/subject/bwexictx.html