您的位置:首页 > 编程语言 > Java开发

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;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: