链表翻转
来源:互联网 发布:历史数据库 编辑:程序博客网 时间:2024/05/31 11:04
需求:
翻转链表,比如给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
分析:
1、思路一
利用集合实现链表的翻转,遍历链表,将每个数字存到集合中,翻转集合,然后重新给链表节点赋值
2、思路二
原地翻转。遍历链表,将每个节点的下一个节点next临时保存,创建prev节点,用来存储当前节点的新的下一个节点,初始化为null,不断更新prev和head头结点,实现翻转
代码:
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */public class Solution { /* * @param head: n * @return: The new head of reversed linked list. */ public ListNode reverse(ListNode head) { // write your code here /*思路一:使用集合完成链表的翻转 //遍历链表,将数字存到list集合中,然后翻转,然后给链表重新赋值 if(head == null) { return null; } List<Integer> list = new ArrayList<Integer>(); ListNode p = head; while(p != null) { list.add(p.val); p = p.next; } //翻转集合 Collections.reverse(list); //遍历集合,给链表重新赋值 p = head; for(Integer num : list) { p.val = num;//重新赋值 p = p.next; } return head; */ //思路二:原地翻转链表,本质就是指针方向的改变 ListNode prev = null; while(head != null) { ListNode temp = head.next; head.next = prev; prev = head; head = temp; } return prev; }}
阅读全文
0 0
- 无情链表的创建,,翻转翻转
- 链表翻转程序
- 链表翻转
- 链表翻转
- 链表翻转
- 翻转单向链表
- 翻转链表
- 原地翻转链表
- 链表的翻转
- 链表翻转
- 翻转部分链表
- 链表翻转
- 链表翻转
- c++翻转链表
- 翻转链表
- 链表翻转
- 翻转链表
- 链表翻转
- php微信企业付款到个人零钱
- protobuf无法使用open函数打开文件
- Failed to execute goal org.apache.maven.plugins
- cherry-pick 多个commit
- 指针与字符串
- 链表翻转
- 11.15第十一课
- 配置Spring连接mysql数据库
- Ubuntu 中安装 IDEA 报错:Warning the selected directory is not a valid tomcat home
- 如何下载行政区划边界?
- 如何利用openUrl打开另外一个app
- 移动端UI界面设计:APP字体排版设计的七个原则
- const T、const T*、T *const、const T&、const T*& 的区别
- python使用sqlaclchemy关于中文报错