题目描述:输入一个链表,从尾到头打印链表每个节点的值。
本题在开头用注释形式给出了链表类的成员变量名。
我的想法:
无论哪一种,最开始都是循环遍历得到链表的长度n。
第一种循环n次输出n个节点值;输出方法是嵌套一个循环,每次从head开始,时间复杂度为O(n^2)。
第二种是将链表改造为一个循环链表,然后用两层循环,第二层循环的第一次循环从head开始,循环n次,输出节点值,第二次循环从最后一个开始,循环n次,输出节点值...时间复杂度也是O(n^2),但实际上循环次数比第一种更多。
第三种是将链表改造为一个双向的链表,在链表类中添加一个私有成员指针变量,指向上一个节点,时间复杂度为O(n),然而该题目中链表类的定义已经固定,这种方法不可取。
遇到的问题:
第一次没有考虑到给出的链表也许为空的情况,导致段错误。于是加上了一个特判。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* current_node = head;
int cnt = 0;
if (current_node == NULL) {
vector<int> result(cnt);
return result;
}
cnt = 1;
while (current_node -> next != NULL) {
cnt++;
current_node = current_node -> next;
}
current_node -> next = head;
current_node = head;
vector<int> result(cnt);
for (int i = 0; i < cnt; i++) {
for (int now = 1; now < cnt; now++) {
current_node = current_node -> next;
}
result[i] = current_node -> val;
}
return result;
}
};