Reverse Linked List

题目:

  Reverse a singly linked list.

cpp:

class Solution {
public:
   ListNode* reverseList(ListNode* head) {

        if(!head || !head->next) return head;
        ListNode *p1 = head;
        ListNode *p2 = head->next;
        ListNode *p3 = head->next->next;
        p1->next = nullptr;
        while(p3){
            p2->next = p1;
            p1 = p2;
            p2 = p3;
            p3 = p3->next;
        }
        p2->next = p1;
        return p2;
    }
};

python

class Solution(object):
    def reverseList(self,head):
               if not head or not head.next:
            return head;
        
        p1,p2,p3 = head,head.next,head.next.next
        p1.next = None
        
        while p3:
            p2.next = p1
            p1 = p2
            p2 = p3
            p3 = p3.next
        p2.next = p1
        return p2

  

原文地址:https://www.cnblogs.com/wxquare/p/5223811.html