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);
}
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;
}
}