剑指offer_JZ6 从尾到头打印链表 JZ24 反转链表

JZ6 从尾到头打印链表

在这里插入图片描述

解法一 使用栈

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> s;
        vector<int> result;
        ListNode* node = head;
        while(node != NULL){
            s.push(node->val);
            node = node ->next;
        }
        while(!s.empty()){
            result.push_back(s.top());
            s.pop();
        }
        return result;
    }
};

解法二 递归

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    void recursion(ListNode* node,vector<int>& result){
        if(node != NULL){
            recursion(node->next, result);
            result.push_back(node->val);
        }
    }
    vector<int> printListFromTailToHead(ListNode* head) {    
        vector<int> result;
        recursion(head,result);
        return result;
    }
};

JZ24 反转链表

在这里插入图片描述

解法一 使用栈,构造新链表

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:

    ListNode* ReverseList(ListNode* pHead) {
        stack<ListNode*> s;

        ListNode* node = pHead;
        while(node != NULL){
            s.push(node);
            node = node ->next;
        }
        if(s.empty()){return NULL;}
        ListNode* ans = s.top();
        s.pop();
        ListNode* head = ans;
        while(!s.empty()){
            head->next = s.top();           
            s.pop();
            head = head ->next;
        }
        head->next = NULL;
        return ans;
    }
};

解法二 双指针

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* ans = NULL;
        while(pHead != NULL){
            ListNode* tmp = pHead->next;
            pHead->next = ans;
            ans = pHead;
            pHead = tmp;
        }
        return ans;
    }
};

解法三 递归

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
       if(pHead == NULL|| pHead ->next == NULL){
           return pHead;
       }
        ListNode* ans = ReverseList(pHead->next);
        pHead->next->next = pHead;
        pHead->next = NULL;
        return ans;
    }
};

参考动画演示+多种解法 206. 反转链表

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值