《从头再来》剑指offer.06 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
我有三种方法弄死他!三种!
第一种方法:回溯算法。大体的思想就是只要链表的头节点没有到最后,就一直重复的调用下一位。直到头节点到最后的位置,然后就返回上一层,并将当前结点的值压入数组。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 void backtrack(vector<int> &res, ListNode* head){ 12 if(head == nullptr) return ;//递归调用的返回条件,当头节点为null的时候,返回上一层 13 backtrack(res, head->next);//调用下一个结点 14 res.push_back(head->val);//返回上一层后,将当前结点的值压入数组 15 } 16 vector<int> reversePrint(ListNode* head) { 17 vector<int> res;//定义结果数组 18 backtrack(res,head);//调用 19 return res; 20 21 } 22 };
第二种方法:用栈来辅助完成。大体思想就是新建一个结点,并将头节点赋给这个结点。然后如果此节点不为null,则将此节点的值压入栈中,然后结点后移一位。当将全部结点的值压入栈以后,开始将栈顶元素依次返回到数组中,最后返回整个数组。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<int> reversePrint(ListNode* head) { vector<int> res; stack<int> stk; ListNode *cur = head; while(cur != nullptr){ stk.push(cur->val); cur = cur->next; } while(!stk.empty()){ res.push_back(stk.top()); stk.pop(); } return res; } };
第三种方法:利用vector的insert函数。思路是只要当前结点没有到链表的末尾,就将当前结点的值插入数组的头部,每次都插入现有数组的头部,到最后返回数组即可。
insert(pos, val):就是将val插在指定的位置的前一个位置。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<int> reversePrint(ListNode* head) { vector<int> res; ListNode *cur = head; while(cur != nullptr){ res.insert(res.begin(),cur->val); cur = cur->next; } return res; } };
代码比较简单,就不做解释了。
《从头再来》

浙公网安备 33010602011771号