Reverse singly linked list using Java
2016-06-29 15:12
330 查看
public class SinglyLinkedList {
static final class Node{
Object value;
Node next;
public Node(Object value, Node next){
this.value = value;
this.next = next;
}
}
public static void main(String[] args){
Node head = createList();
traverse(head);
System.out.println();
head = reverse(head);
traverse(head);
}
/**
*current 总是指向原来的head
**/
public static Node reverse(Node head){
if(head == null || head.next == null){
return head;
}
Node current = head;
Node next, nextNext;
while(current.next != null){
next = current.next;
nextNext = next.next;
next.next = head;
head = next;
current.next = nextNext;
}
return head;
}
public static void traverse(Node head){
if(head == null){
return;
}
Node current = head;
while(current != null){
System.out.print(current.value + ",") ;
current = current.next;
}
}
public static Node createList(){
Node n6 = new Node(6,null);
Node n5 = new Node(5,n6);
Node n4 = new Node(4,n5);
Node n3 = new Node(3,n4);
Node n2 = new Node(2,n3);
Node head = new Node(1,n2);
return head;
}
}
static final class Node{
Object value;
Node next;
public Node(Object value, Node next){
this.value = value;
this.next = next;
}
}
public static void main(String[] args){
Node head = createList();
traverse(head);
System.out.println();
head = reverse(head);
traverse(head);
}
/**
*current 总是指向原来的head
**/
public static Node reverse(Node head){
if(head == null || head.next == null){
return head;
}
Node current = head;
Node next, nextNext;
while(current.next != null){
next = current.next;
nextNext = next.next;
next.next = head;
head = next;
current.next = nextNext;
}
return head;
}
public static void traverse(Node head){
if(head == null){
return;
}
Node current = head;
while(current != null){
System.out.print(current.value + ",") ;
current = current.next;
}
}
public static Node createList(){
Node n6 = new Node(6,null);
Node n5 = new Node(5,n6);
Node n4 = new Node(4,n5);
Node n3 = new Node(3,n4);
Node n2 = new Node(2,n3);
Node head = new Node(1,n2);
return head;
}
}
相关文章推荐
- Java pattern & Matcher 的使用详解
- JavaSE 基础 第19节 如何使用数组
- java接口与内部类
- MyEclipse自动补全与快捷键设置
- 关于运行期异常:Failed to instantiate [java.util.List]: Specified class is an interface
- 调用webservice 中出现的问题
- java内存机制
- JavaSE 基础 第18节 数组的创建以及初始化
- 浅析Java中的final关键字
- Struts2 拦截器中实现对数据进行数据库操作
- java 中try catch finally 与return位置的关系
- hibernate getCurrentSession和Spring事务管理集成
- Java内部类详解
- 如何理解java堆栈
- 160621、Java注解教程及自定义注解
- java单例学习
- 浅析Spring和MyBatis整合及逆向工程
- 实习杂记(26):Java 8十个lambda表达式案例
- 160615、Spring3 MVC 拦截器拦截不到的问题
- java获取服务器地址