package singlelist;
public class Node {
private Object data;
private Node next;
public Node(Object data) {
this.data = data;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public Node getNext() {
return next;
}
public void setData(Object data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
}
package singlelist;
public class Test {
public static void main(String[] args) {
Node lastNode = new Node(44);
Node node3 = new Node(33,lastNode);
Node node2 = new Node(22,node3);
Node headNode = new Node(11,node2);
System.out.print("反转之前的单链表:");
print(headNode);
System.out.println();
System.out.print("反转之后的单链表:");
Node reverse = reverseLinkedList(headNode);
print(reverse);
}
public static void print(Node headNode){
Node tempNode = headNode;
while (tempNode!=null){
System.out.print(tempNode.getData()+" ");
tempNode = tempNode.getNext();
}
}
public static Node reverseLinkedList(Node headNode){
if (headNode==null||headNode.getNext()==null){
return headNode;
}
Node reverse = null;
while (headNode!=null){
Node nextNode = headNode.getNext();
headNode.setNext(reverse);
reverse = headNode;
headNode = nextNode;
}
return reverse;
}
}