[leetcode题解]206-Reverse-Linked-List

简单链表逆置,这个在面试中多次要求被写,是在搞不懂这么简单的问题为什么要放在面试中,直接用头插法就可以了,下面是c++和python代码

c++代码:

class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        ListNode *pre = new ListNode(-1);
        
        ListNode *p = head;
        while(p != NULL)
        {
            ListNode *t = p->next;
            p->next = pre->next;
            pre->next = p;
            p = t;
        }
        return pre->next;
    }
};

python代码:

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        
        pre = ListNode(-1)
        while head != None:
            t = head.next
            head.next = pre.next
            pre.next = head
            head = t
        return pre.next

本文遵从CC3.0协议转载请注明:转自凌风技术站

本文标题:[leetcode题解]206-Reverse-Linked-List

本文链接地址:http://www.iaccepted.net/algorithm/leetcode/56.html

相关文章



发表评论

电子邮件地址不会被公开。 必填项已用*标注