输入一个链表,从尾到头打印链表每个节点的值

来源:互联网 发布:软件开发售后服务内容 编辑:程序博客网 时间:2024/05/29 10:42
/*输入一个链表,从尾到头打印链表每个节点的值 */#include <iostream>#include <stdio.h>#include <vector>using namespace std;typedef struct List{int node;List *next;}Node,*linkList;linkList linkListCreat(){//链表初始化Node* L = (Node*)malloc(sizeof(Node));if(L == NULL)printf("....");L->next = NULL;Node *node_;int listSize = 0;printf("请输入需要的链表节点:");scanf("%d",&listSize);for (int i=0; i<listSize; i++){int mid = 0; scanf("%d",&mid);node_ = (Node *)malloc(sizeof(Node));node_->node = mid;node_->next = L->next;L->next = node_;}return L;}int main(){linkList list,start;list = linkListCreat();printf("链表从尾到头逆序输出结果为:");for(start = list->next; start != NULL; start = start->next)printf("%d ",start->node);printf("\n");return 0;}

剑指Offer题解:

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> res;    vector<int> printListFromTailToHead(ListNode* head) {        if(head != NULL){            if(head->next != NULL){                printListFromTailToHead(head->next);            }            res.push_back(head->val);        }        return res;    }};


阅读全文
0 0
原创粉丝点击