数据结构和算法分析算法提高之LeetCode刷题

反转链表

2020-03-02  本文已影响0人  _阿南_

题目:

反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

题目的理解:

新建一个链表,然后循环给定的链表来获取每一个节点,将节点倒序添加到新链表上。

python实现

# 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 head is None or head.next is None:
            return head
        
        current = head.next
        result = ListNode(head.val)
        
        while current is not None:
            temp = current.next
            
            current.next = result
            result = current
            
            current = temp
            
        return result

提交

哇哈哈

// END 无薪待业 !_!

上一篇 下一篇

猜你喜欢

热点阅读