Written test questions---linked list reversal

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # return 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
Set two temporary values, respectively save this node and the next node, then flip over. Because last finally represents the end of the original linked list, so just return last

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588196&siteId=291194637