算法名称:链表反转
实现方法:按顺序交换元素
级别:基本(入门级)
package test.algorithms;
class Node{
public Node(String name){
this.name = name;
}
public String name;
public Node next;
public void output(){
Node t = this ;
while( t != null ){
System.out.println(t.name);
t = t.next;
}
}
}
public class LinkedTable {
private Node[] swap(Node before,Node after){
if(after == null){
return new Node[]{null,null};
}
Node childOfAfter = after.next;
after.next= before;
return new Node[]{after,childOfAfter};
}
private Node reverse(Node head){
if(head.next == null){
return head;
}
Node before = head;
Node after = before.next;
Node[] temp = null;
while( ( (temp=swap(before,after) )[1]) !=null ){
before = temp[0];
after = temp[1];
}
head.next = null;
return temp[0];
}
public static void main(String[] args) {
Node head = new Node("1");
Node n2 = new Node("2");
Node n3 = new Node("3");
Node n4 = new Node("4");
Node n5 = new Node("5");
Node n6 = new Node("6");
head.next = n2;
n2.next= n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
LinkedTable linktable = new LinkedTable();
Node n = linktable.reverse(head);
n.output();
}
}