题目

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

限制:

0 <= 节点个数 <= 5000

注意:本题同【LeetCode】206. 反转链表

思路一:反转链表元素

取出链表中元素放入vector中,然后将vector中元素逆向存入链表中。

  1. 遍历链表,用vector存放数组元素。
  2. 再次遍历链表,从vector尾部读取元素依次放入链表中。

代码

时间复杂度:O(n)

空间复杂度:O(n)

ListNode* reverseList(ListNode* head) {
if (head == nullptr) {
return head;
}
vector<int> res;
ListNode *pNode = head;
while (pNode != nullptr) {
res.push_back(pNode->val);
pNode = pNode->next;
}
vector<int>::reverse_iterator iter = res.rbegin();
pNode = head;
while (pNode != nullptr) {
pNode->val = *iter;
iter++;
pNode = pNode->next;
}
return head;
}

思路二:迭代

需要调整当前元素指针指向前一个元素,必须先存储其前一个元素,另外为了继续遍历链表,在改动指针前,还需要存储下一个节点。新头结点为最后保存的前一个元素。

代码

时间复杂度:O(n)

空间复杂度:O(1)

ListNode* reverseList(ListNode* head) {
if (head == nullptr) {
return head;
}
ListNode *cur = head;
ListNode *pre = nullptr;
while (cur != nullptr) {
ListNode *next = cur->next;//保存当前节点下一个节点
cur->next = pre;//反转指针
pre = cur;//分别移动pre和cur
cur = next;
}
return pre;
}

思路三:递归

通过递归反转链表后面的元素,递归终止条件为当前节点为空或下一个节点为空。现在对头节点进行反转,假设链表此时为:

head -> n1 <- n2... <-n

对头结点进行反转:head->next->next = head;

然后将头节点next设为nullptr。

代码

时间复杂度:O(n)

空间复杂度:O(n),由于使用递归,会使用隐式栈空间,递归深度可能达到n层。

ListNode* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode *p = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return p;
}

最新文章

  1. quartz集群报错but has failed to stop it. This is very likely to create a memory leak.
  2. Quartz资源收藏
  3. centos6.7 install chrome
  4. Oracle 如何让别人能够连接到你的数据库
  5. Netty之ChannelOption
  6. Qt探秘——谈ui文件的用法
  7. 09_android入门_採用android-async-http开源项目的GET方式或POST方式实现登陆案例
  8. jsp的开发模式
  9. Unity3D中的shader基础知识
  10. ubuntu安装yaf
  11. 教你快速录制gif动图
  12. 《Miracle_House》团队项目系统设计改进
  13. sublime----------快捷键的记录
  14. linux上java解加密(AES/CBC)异常:java.lang.SecurityException: JCE cannot authenticate the provider BC办法
  15. 【2017-2-23】C#switch case分支语句,for循环语句
  16. ps基础学习笔记一
  17. 【Unity笔记】UGUI的Text文本框的大小随着文本字数变化
  18. Windows2008安装WebSphere 6.1提示此安装程序不能在图形方式中运行
  19. 【原创】MySQL常用脚本整理
  20. Codeforces Round #228 (Div. 1) C. Fox and Card Game 博弈

热门文章

  1. Linux-使用之vim出现的问题
  2. java并发AtomicIntegerFieldUpdater
  3. SC.Lab3对于Factory的构建过程(from HIT)
  4. 八 Hibernate延迟加载&amp;抓取策略(优化)
  5. vue 使用 element-ui 时报错ERROR in ./node_modules/element-ui/lib/theme-chalk/fonts/element-icons.ttf
  6. 今日份学习:写一些代码 (Spring+AOP+Redis+MySQL练习)
  7. 【Winform】键 盘 事 件
  8. Zabbix——自动监控
  9. mac搭建nginx
  10. Run K8s / 安装指南