ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

洛谷 U228721:反转单链表

洛谷 U228721:反转单链表 【题目来源】https://www.luogu.com.cn/problem/U228721【题目描述】题目给出一串数字首先你需要把这些数字构造成一个单链表然后将此单链表反转。【输入格式】一行一串数字。【输出格式】一行一串数字空格分隔。【输入样例】1 2 3【输出样例】3 2 1 None【说明/提示】注意本题要求答案最后加上None哦。【算法分析】● 单链表的相关代码若借助示意图来写会更容易。● 若有两个指针 a 与 b且 ab则表示 a 指向 b 指向的结点。这一点对快速绘制单链表的示意图有很多帮助。【算法代码一】本代码由于用到 while(cinx)所以在输入完样例 1 2 3 后需要按回车键然后再按下 CtrlZ 键才能看到运行结果 3 2 1 None。#include bits/stdc.h using namespace std; const int maxn1e55; int e[maxn],ne[maxn],idx,h-1; void add(int x) { e[idx]x,ne[idx]h,hidx; } int main() { int x; while(cinx) { add(x); } for(int ih; i!-1; ine[i]) { coute[i] ; } coutNoneendl; return 0; } /* in: 5 6 3 9 2 1 out: 1 2 9 3 6 None */【算法代码二】#includebits/stdc.h using namespace std; struct LNode { int data; LNode *next; }; int main () { LNode *Lnew LNode; L-nextNULL; int x; while(cinx) { LNode *p; pnew LNode; p-datax; p-nextL-next; L-nextp; } while(L-next) { coutL-next-data ; L-nextL-next-next; } coutNoneendl; return 0; } /* in: 1 2 3 out: 3 2 1 None */【算法代码三】#include bits/stdc.h using namespace std; vectorint v; int main() { int x; while(cinx) { v.push_back(x); } for(int iv.size()-1; i0; i--) { coutv[i] ; } coutNone; return 0; } /* in: 1 2 3 out: 3 2 1 None */【参考文献】https://blog.csdn.net/hnjzsyjyj/article/details/108586756
返回列表