单链表反转
package com.etime;
public class ReverseLinkedList {
public static void main(String[] args) {
Node head = new Node();
head.setData(1);
Node node2 = new Node();
node2.setData(2);
head.setNext(node2);
Node node3 = new Node();
node3.setData(3);
node2.setNext(node3);
System.out.println(head);
Node revers = revers(head);
System.out.println(revers);
}
public static Node revers(Node head){
Node currentNode = head;
Node currentNext = null;
if(currentNode.hasNext()){
currentNext = head.getNext();
}else {
return currentNode;
}
while (currentNode.hasNext()){
Node temp = null;
if(currentNext.hasNext()){
temp = currentNext.getNext();
}else {
break;
}
head.setNext(null);
currentNext.setNext(currentNode);
currentNode = currentNext;
currentNext = temp;
}
currentNext.setNext(currentNode);
return currentNext;
}
static class Node{
private Integer data;
private Node next;
public Node() {
}
public Node(Integer data, Node next) {
this.data = data;
this.next = next;
}
public void setData(Integer data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
public Integer getData(){
return this.data;
}
public Node getNext() {
return next;
}
public boolean hasNext(){
return next != null;
}
@Override
public String toString() {
if(this.hasNext()){
return this.data.toString() + "," +this.next.toString();
}else {
return this.data.toString();
}
}
}
}