python链表反转

题目

python链表反转

思路

题目的重点是:实现把一个结点直接插在头结点之前。直接去插入实现起来很复杂,而且删除结点也比较麻烦,于是先设定一个空指针rev = None,通过遍历链表一步步插入。

代码

# 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:
		rev = None
		while head:
			rev,rev.next,head = head,rev,head.next
		return rev
#循环里的交换语句在交换时不影响其他交换的值,另一种写法如下
# 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:
        rev = None
        while head:
            new = rev
            rev = head
            head = head.next
            rev.next = new
        return rev
上一篇:【Leetcode】9. 回文数


下一篇:Ubuntu12.04安装ThinkPad T440p笔记本网卡驱动