Q06链表逆转打印

链表逆转打印

注意事项

  • 执行插入操作时,传入函数的链表头应该是指针的指针,因为在空链表中插入节点时,需要修改链表头指针!

Q6 从尾到头打印链表

逆转的三种实现思路:

  • 使用栈的数据结构
  • 将栈转换为递归
  • 修改链表的节点,使其指向反向

递归方法

//递归方法
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    void printListReverseRecursively(vector<int>& out, ListNode* head)
    {
        if(head!=nullptr)
        {
            if(head->next!=nullptr)
            {
                printListReverseRecursively(out, head->next);
            }
            out.push_back(head->val);
        }
    }
    
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> arr;
        printListReverseRecursively(arr, head);
        return arr;
    }
};

逆转链表方法

注意:void reverseList(ListNode** phead)一定是指针的指针!!因为要修改head。返回时也要记得修改phead!

    void reverseList(ListNode** phead)
    {
        ListNode* head = *phead;
        ListNode* pre = nullptr;
        while(head!=nullptr)
        {
            ListNode* nextnode = head->next;
            head->next = pre;
            pre = head;
            head = nextnode;
        }
        *phead = pre;
    }
    
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> arr;
        //printListReverseRecursively(arr, head);
        reverseList(&head);
        while(head!=nullptr)
        {
            arr.push_back(head->val);
            head = head->next;
        }
        return arr;
    }

栈的方法

    
    vector<int> getReverseValueOfList(ListNode* head)
    {
        stack<int> stackArr;
        vector<int> arr;
        while(head!=nullptr)
        {
            stackArr.push(head->val);
            head = head->next;
        }
        while(!stackArr.empty())
        {
            arr.push_back(stackArr.top());
            stackArr.pop();
        }
        return arr;
    }
发布了48 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/mhywoniu/article/details/104906193