单链表反转--java版
来源:互联网 发布:java编程软件有哪些 编辑:程序博客网 时间:2024/06/05 19:56
单链表反转–java版
思路
head—>a—->b—->c
变成:
head—>c—->b—->a
我们可以用循环的方式去实现,遍历一次链表即可。
1.用一个临时变量tmp存储 a的下一个元素b,a的next指向null,即”由头变尾”,head指向null。
head—->null
a b—->c
tmp—->b
2.因为此时tmp就是b,所以将tmp指向tmp的下一个元素c。将b next指向a
head—->null
a <—– b c
tmp—->c
3.因为此时tmp就是c,所以将tmp指向tmp的下一个元素null。将c next指向b
head—->null
a <—– b <—– c
tmp—->null
4.head——->c
/** * 链表反转 * @author guohui * */public class ReverLink { public static void main(String[] args) { Node<Integer> head = new Node<Integer>(); Node<Integer> n1 = new Node<Integer>(); Node<Integer> n2 = new Node<Integer>(); Node<Integer> n3 = new Node<Integer>(); head.next=n1; n1.data=1; n1.next=n2; n2.data = 2; n2.next = n3; n3.data = 3; reverse(head); Node<Integer> cur = head; while(cur!=null){ System.out.println(cur.data); cur = cur.next; } } /** * 链表反转 * @param head */ public static void reverse(Node<Integer> head) { if(head ==null ){ return ; } boolean isFisrt = true; Node<Integer> pre = head; Node<Integer> cur = head.next; Node<Integer> tmp; while(cur!=null){ tmp = cur.next; if(!isFisrt){ cur.next = pre; }else{ isFisrt = false; cur.next = null; } pre = cur; cur = tmp; } head.next = pre; }}/** * 链表数据结构 * @author guohui * * @param <T> */public class Node<T> { public Node next; public T data;}
阅读全文
0 0
- 单链表反转--java版
- Java单链表反转与部分反转
- Java实现单链表反转
- Java实现反转单链表
- Java-反转单链表
- Java反转单链表
- Java 反转单链表
- java反转单链表
- Java反转单链表(code)
- Java反转单链表(code)
- Java反转单链表
- java反转单链表
- 反转单链表(Java描述)
- 单链表反转--Java实现
- Java实现单链表反转
- java 单链表反转详解
- 单链表反转java
- Java单链表反转
- AS——使用Code iris生成uml
- 2-JavaScript设计模式——commonUtils工具库之继承函数
- vue2.0详细目录结构注解
- mysql数据创建用户及授权
- 平衡二叉树的判断
- 单链表反转--java版
- Week Training: 62 Unique Paths
- 6.1-6.4 JLL--实习日志--filter_box,复选框+basic function
- HttpClient使用详解
- 编程第一百天
- 51541327
- 详解单例模式
- 多线程-定时器的概述和使用
- 慕课网学习Python进阶教程,包括(函数式编程、模块、面向对象编程、类的继承、定制类)