剑指offer24:反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

# -*- coding:utf-8 -*-
class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        last=None
        while pHead:
            tmp=pHead.next
            pHead.next=last
            last=pHead
            pHead=tmp
        return last
链接: https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
来源:牛客网

pHead始终指向要反转的结点 last 指向反转后的首结点 每反转一个结点,把pHead结点的下一个结点指向last, last指向pHead成为反转后首结点, 再把pHead向前移动一个结点直至None结束




猜你喜欢

转载自blog.csdn.net/zhangjiaxuu/article/details/80911286