牛客网&剑指Offer&从尾到头打印链表
代码实现1
#include<iostream>
#include<vector>
using std::vector;
using std::cin;
using std::cout;
using std::endl;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) { }
ListNode() {}; //如果不重新定义一个默认构造函数,那么下面ListNode *s = new ListNode;代码将会出错,因为不符合此构造函数格式ListNode(int x)
};
// 创建单链表
ListNode *creat()
{
ListNode *head, *p;
head = new ListNode;
p = head;
int x, cycle = 1;
while (cycle)
{
cout << "Please input the data for single linker : ";
cin >> x;
if (x != 0)
{
ListNode *s = new ListNode;
s->val = x;
cout << "Input data : " << x << endl;
p->next = s;
p = s;
}
else
{
cycle = 0;
cout << "Input done! " << endl;
}
}
head = head->next; //不可缺少,作用为将已经创建好得第一个节点地址整体赋值给head
p->next = NULL;
return head;
}
// 单链表测长
int length(ListNode *head)
{
int n = 0;
ListNode *p = head;
while (p != NULL)
{
p = p->next;
n++;
}
return n;
}
// 单链表打印
void printL(ListNode *head)
{
ListNode *p = head;
while (p != NULL)
{
cout << "Single Linker data is " << p->val << endl;
p = p->next;
}
}
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
int length = 0;
int len = 0;
//求链表的长度
ListNode *p = head;
while (p != NULL)
{
p = p->next;
length++;
}
len = length;
vector<int> test_value(length);
ListNode *p1 = head;
while (p1 != NULL)
{
test_value[--length] = p1->val;
p1 = p1->next;
}
for (int i = 0; i < len ; i++)
cout << test_value[i] << ",";
cout << endl;
return test_value;
}
};
int main()
{
vector<int> test_value1(100);
Solution test;
int len = 0;
cout << "***创建单链表***" << endl;
ListNode *head = creat();
cout << endl;
cout << "***单链表长度***" << endl;
len = length(head);
cout << "单链表长度为" << len << endl;
cout << "***打印单链表***" << endl;
printL(head);
cout << endl;
cout << "***test !!!***" << endl;
test_value1 = test.printListFromTailToHead(head);
for(int i = 0; i < len; i++)
cout << test_value1[i] << ",";
}
代码实现2
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
int len = 0;
int index = 0;
std::stack<ListNode*>nodes;
ListNode* pNode = head;
while(pNode != nullptr)
{
len++;
nodes.push(pNode);
pNode = pNode->next;
}
vector<int>test_value(len);
while(!nodes.empty())
{
pNode = nodes.top();
test_value[index++] = pNode->val;
nodes.pop();
}
return test_value;
}
};
编程笔记
- 代码实现1解题思路:1.求得链表长度,构建一定内存的数组;2.从头到尾遍历链表,依次将遍历的数值从尾到头放入数组,再返回数组(如果返回值为链表类型也需要会操作);
- 代码实现2解题思路:遍历列表,反序输出,典型的“后进先出”,可以使用栈;
- 熟悉使用链表的基本操作
链表基础操作参考链接1
链表基础操作参考链接2
链表排序操作参考链接 - 熟悉使用栈的基础操作,后序详细介绍。