翻转单链表(leetcode206)

一:解题思路

方法一:用递归的方法去解决。Time:O(n),Space:O(n)

方法二:用双指针的方法去解决。Time:O(n),Space:O(1)

二:完整代码示例 (C++、Java、Python)

方法一C++:

class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        ListNode* ret = NULL;
        if (head == NULL)
        {
            ret = head;
        }
        else if (head->next == NULL)
        {
            ret = head;
        }
        else
        {
            ListNode*  guard = head->next;
            ret = reverseList(guard);
            guard->next = head;
            head->next = NULL;
        }

        return ret;
    }
};

方法二C++:

class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        if (head == NULL || head->next==NULL) return head;

        ListNode* pre = NULL;
        ListNode* cur = head;

        while (cur != NULL)
        {
            ListNode* next = cur->next;

            cur->next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }
};

方法一Java:

class Solution {
        public ListNode reverseList(ListNode head) 
        {
               ListNode ret=null;
               if(head==null)
               {
                   ret=head;
               }
               else if(head.next==null)
               {
                   ret=head;
               }
               else
               {
                   ListNode guard=head.next;
                   ret=reverseList(guard);
                   guard.next=head;
                   head.next=null;
               }
               
               return ret;
        }
    }

方法二Java:

class Solution {
        public ListNode reverseList(ListNode head) 
        {
               if(head==null || head.next==null) return head;
               
               ListNode pre=null;
               ListNode cur=head;
               
               while(cur!=null)
               {
                   ListNode next=cur.next;
                   cur.next= pre;
                   
                   pre=cur;
                   cur=next;
               }
               
               return pre;
        }
    }

方法一Python:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        ret=None
        if head == None:
            ret=head
        elif head.next == None:
            ret=head
        else:
            guard=head.next
            ret=self.reverseList(head.next)
            guard.next=head
            head.next=None
        return ret

方法二Python:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head==None: return head
        if head.next==None: return head
        
        pre,cur=None,head
        while cur is not None:
            next=cur.next
            cur.next=pre
            pre=cur
            cur=next
        return pre

 

posted @ 2020-03-08 21:30  repinkply  阅读(147)  评论(0)    收藏  举报