zoukankan      html  css  js  c++  java
  • Leetcode(206)-反转链表

    反转一个单链表。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL

    思路:反转链表很简单,经常使用stack的,一下子就会想到用stack存储链表的节点,然后反向输出

    ListNode* reverseList(ListNode* head)
    {
        stack<ListNode*> s;
        ListNode* p=head,*newhead,*pnew;
        newhead=NULL;
        while(p)
        {
            s.push(p);
            p=p->next;
        }
        while(!s.empty())
        {
            if(newhead==NULL)
            {
                newhead=pnew=s.top();
                s.pop();
            }
            else
            {
                pnew->next=s.top();
                s.pop();
                pnew=pnew->next;
            }
        }
        if(newhead)
            pnew->next=NULL;
        return newhead;
    }

    另外还有一种递归的方式

    ListNode *reverseList(ListNode *head,ListNode *pNewHead)  
    {  
        if(head == NULL)  
            return pNewHead;  
        ListNode *next = head->next;  
        head->next = pNewHead;  
        return reverseList(next,head);  
    }  
    ListNode* reverseList(ListNode* head) {  
        return reverseList(head,NULL);  
    } 
  • 相关阅读:
    矩阵价值和
    排列组合问题
    X国的军队
    石子合并加强版
    P1042 乒乓球
    Dinner 点餐
    一文看尽图像分类问题
    [Udemy] Recommender Systems and Deep Learning in Python
    推荐系统学习
    [NLP] 酒店名归类
  • 原文地址:https://www.cnblogs.com/mini-coconut/p/9111537.html
Copyright © 2011-2022 走看看