Reverse Linked List

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

  

以上是关于Reverse Linked List的主要内容,如果未能解决你的问题,请参考以下文章

206. Reverse Linked List

链表-Reverse Linked List

206. Reverse Linked List

Reverse Linked List

206. Reverse Linked List

No 206, Reverse Linked List