|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2020-5-8 18:02 编辑
题目描述:
- 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
-  
- 示例 1:
- 输入:head = [1,3,2]
- 输出:[2,3,1]
-  
- 限制:
- 0 <= 链表长度 <= 10000
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- #include <stack>
- #include <iostream>
- #include <vector>
- using namespace std;
- struct ListNode{
- int value;
- ListNode *next;
- ListNode(int x) : value(x), next(NULL) {}
- };
- void printList(ListNode* head){
- ListNode* temp = head;
- while(temp -> next != NULL){
- temp = temp -> next;
- cout << temp -> value << " ";
- }
- cout << endl;
- }
- vector<int> solution(ListNode* head){
- vector<int> result;
- stack<int> out;
- ListNode* temp = head -> next;
- while(temp -> next != NULL){
- out.push(temp -> value);
- temp = temp -> next;
- }
- out.push(temp -> value);
- while(!out.empty()){
- result.push_back(out.top());
- out.pop();
- }
- return result;
- }
- int main(void){
- int number;
- ListNode* head = new ListNode(0);
- ListNode* temp = head;
- while(cin >> number){
- ListNode* node = new ListNode(number);
- temp -> next = node;
- temp = node;
- }
- cout << "finish!" << endl;
- printList(head);
- vector<int> result = solution(head);
- for(int i = 0; i < result.size(); i++){
- cout << result[i] << " ";
- }
- cout << endl;
-
- return 0;
- }
复制代码
参考链接:http://www.manongjc.com/article/61445.html
注意事项:
1.这里自己定义了一个head为0。
2.要定义一个temp指针=head,防止后续head指针变换。
3.单链表中各元素地址是不连续的,所以这里用了一个new生成新node。 |
|