【002】链表翻转
来源:互联网 发布:哪个软件足球比赛录像 编辑:程序博客网 时间:2024/06/06 13:12
题目描述
翻转一个链表
例如:1 2 3 4
输出:4 3 2 1
输入输出
输入
- 第一行是n; 表示链表长度
第二行是n个整数,表示链表每一位所存储的内容
输出- 针对每组输出,输出翻转后的链表的内容
示例输入
4
1 2 3 4
示例输出
4 3 2 1
题目分析
链表翻转是比较经典的面试题目,其中也有很多坑,要注意NULL和head节点的处理。
这道题有两种解法,迭代和递归,代码如下:
#include <iostream>using namespace std;class Node {public: int num; Node *next; Node():next(NULL) {} Node(int num):num(num), next(NULL) {} void display() { Node *tmp = this; while (tmp) { printf("%d ", tmp->num); tmp = tmp->next; } printf("\n"); }};class Reverse {public: Node* Iteration(Node* &head) { Node *current = head; Node *pre = NULL; while (current != NULL) { Node *next = current->next; current->next = pre; pre = current; current = next; } return pre; } Node *Recursion(Node* &head) { if (head == NULL || head->next == NULL) return head; Node *newHead = Recursion(head->next); head->next->next = head; head->next = NULL; return newHead; }};int main(int argc, char *argv[]) { Node *head = NULL; Node *current = NULL; int n; scanf("%d", &n); while(n--) { int num; scanf("%d", &num); Node *tmp = new Node(num); if (head == NULL) head = tmp; else current->next = tmp; current = tmp; } Reverse re; //head = re.Iteration(head); head = re.Recursion(head); head->display(); return 0;}
0 0
- 【002】链表翻转
- 无情链表的创建,,翻转翻转
- 链表翻转程序
- 链表翻转
- 链表翻转
- 链表翻转
- 翻转单向链表
- 翻转链表
- 原地翻转链表
- 链表的翻转
- 链表翻转
- 翻转部分链表
- 链表翻转
- 链表翻转
- c++翻转链表
- 翻转链表
- 链表翻转
- 翻转链表
- Android学习之Java基础篇day7
- mysql------>使用cmd打开my sql
- 【leetcode】312. Burst Balloons
- android之事件分发机制
- 二叉树已知前序,中序,求后序
- 【002】链表翻转
- 团体程序设计天梯赛L3-010 是否完全二叉搜索树
- ant-design 实现一个登陆窗口
- CentOS搭建PHP服务器之联通网络
- 45-java中的try--catch的使用
- 一个脚本引发的血案
- 多字符串存储的Trie树详解
- 团体程序设计天梯赛L3-011 直捣黄龙
- HDU1027_Ignatius and the Princess II_非模拟做法