笔试题---链表反转

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if not pHead or not pHead.next:
            return pHead
        last = None
        
        while pHead:
            temp = pHead.next
            pHead.next = last
            last = pHead
            pHead = temp
        return last
        
        # write code here
设置两个临时值,分别保存本节点和下一个节点,然后翻转过来。因为last最后表示的是原链表的末尾,所以返回last就好啦

猜你喜欢

转载自blog.csdn.net/mr_ming_/article/details/79450674