码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Linked List

时间:2016-02-27 23:40:13      阅读:333      评论:0      收藏:0      [点我收藏+]

标签:

题目:

  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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!