//单链表反序
public class SingleLinkedListReverse { public static void main(String[] args) {
Node head = new Node(0);
Node temp = null;
Node cur = null; for (int i = 1; i <= 10; i++) {
temp = new Node(i);
if (i == 1) {
head.setNext(temp);
} else {
cur.setNext(temp);
}
cur = temp;
}//10.next = null; Node h = head;
while (h != null) {
System.out.print(h.getData() + "\t");
h = h.getNext();
}
System.out.println(); //反转1
// h = Node.reverse1(head);
// while (h != null) {
// System.out.print(h.getData() + "\t");
// h = h.getNext();
// } //反转2
h = Node.reverse1(head);
while (h != null) {
System.out.print(h.getData() + "\t");
h = h.getNext();
} }
} /*
* 单链表的每一个节点都含有指向下一个节点属性
*/
class Node {
Object data;//数据对象
Node next; //下一节点 Node(Object d) {
this.data = d;
}
Node(Object d, Node n) {
this.data = d;
this.next = n;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
//方法1 head被重置
static Node reverse1(Node head) { Node p = null; //反转后新的 头
Node q = head;
//轮换结果:012,123,234,.... 10 null null
while (head.next != null) {
p = head.next; // 第1个 换成第2个 这时p表示原始序列头中的next
head.next = p.next; // 第2个 换成第3个
p.next = q; //已经跑到第1位置的原第2个的下一个 就要变成 原第1个
q = p; //新的第1个 要变成 当前第一个
}
return p; }
//方法2 head没重置
static Node reverse2(Node head) {
//将中间节点的指针指向前一个节点之后仍然能够继续向后遍历链表
Node p1 = head, p2 = head.next, p3; // 前 中 后
//轮换结果 :012, 123, 234, 345, 456.... 9 10 null
while (p2 != null) {
p3 = p2.next;
p2.next = p1; //指向后 变 指向前
p1 = p2; //2、3向前挪
p2 = p3;
}
head.next = null;//head没变,当输出到0时。再请求0.next 为1
return p1;
}
}

最新文章

  1. 5.2 Array类型介绍
  2. 关于Node.js的总结
  3. MySQL的Order By Rand()的效率问题
  4. 某表含有N个字段超精简模糊查询方法
  5. iLinuxBot: Designing Botnets to Manage Linux Clients
  6. Memcached的一些知识
  7. Java虚拟机:JVM中的Stack和Heap
  8. Lustre文件系统测试——obdfilter-survey测试
  9. MySQL5.6新特性
  10. BZOJ 1029: [JSOI2007]建筑抢修【优先队列+贪心策略】
  11. [HNOI 2015]接水果
  12. sql-我写的或者其他人写的
  13. Android NDK学习(二):编译脚本语法Android.mk和Application.mk
  14. 关于12C中optimizer_adaptive_features参数介绍
  15. Python实现Plugin
  16. Docker技术这些应用场景【转】
  17. 固件_Linux内核
  18. CheckBox使用记录
  19. Java基础之创建实例化对象的方式
  20. C#3.0新特性:隐式类型、扩展方法、自动实现属性,对象/集合初始值设定、匿名类型、Lambda,Linq,表达式树、可选参数与命名参数

热门文章

  1. DataNucleus(通过jpa和jdo接口访问多中数据源)
  2. Ubuntu 终端常用命令
  3. luogu P1056 排座椅
  4. codeforces 314E Sereja and Squares
  5. 【神奇の做法】bzoj2456 mode
  6. 【set】bzoj3715 [PA2014]Lustra
  7. IO 流(File)
  8. yii2 URL重写 nginx的配置
  9. 通过idea 打包 spring maven项目打包为可执行jar包
  10. 开源 免费 java CMS - FreeCMS1.9 移动APP管理 栏目配置