总结的部分题目思路与代码,待完善。
【剑指offer-第二版】部分题目与解答【C++版本】
题目:
从尾到头打印链表
输入一个链表的头节点,从尾到头反过来打印出每个节点的值。链表节点定义如下:
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
解题思路:
1.注意传入函数的是指向链表头的指针,在函数中不应该直接使用这个指针,而是应该用一个指针的临时变量来遍历链表。
2.方法一:使用栈来实现(用栈更好)。
3.方法二:递归在本质上就是一个栈结构,所以也可以用递归来实现。
可以AC的解法一:使用栈来解答【C++版本】
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
};
//
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> resu;
if (head == NULL)
return resu;
ListNode *pNode = head;
stack<int> listStack;
while (pNode != NULL)
{
listStack.push(pNode->val);
pNode = pNode->next;
}
while (!listStack.empty()) {
int tmp = listStack.top();
listStack.pop();
resu.push_back(tmp);
}
return resu;
}
可以AC的解法二:使用递归来解答【C++版本】
//使用递归方法虽然写法简洁,但是其实资源消耗更大
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
};
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> resu;
if (head == nullptr)return resu;
resu = printListFromTailToHead(head->next);
resu.push_back(head->val);
return resu;
}