这里只实现遍历反转,还有一种递归反转这里未实现
/**
* 链表反转
* @author DELL
*
*/
public class LinkReverse {
/**
* @param args
*/
public static void main(String[] args) {
Node n0 = new Node(0);
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
n0.next=n1;
n1.next=n2;
n2.next=n3;
System.out.println(n0.getValue()+"-----"+n1.getValue()+"-----"+n2.getValue()+"-----"+n3.getValue());
Node result = reverse(n0);
System.out.println(result.getValue()+"-----"+result.getNext().getValue()+"-----"+result.getNext().getNext().getValue()+"-----"+result.getNext().getNext().getNext().getValue());
}
/**
* 遍历反转
* @param head
* @return
*/
public static Node reverse(Node head){
if(head==null||head.next==null){
return null;
}
Node pre = head;//前一节点
Node cur = head.getNext();//当前节点
head.setNext(null);
Node next = null;//下一节点
while(cur!=null){
next = cur.getNext();
cur.setNext(pre);
pre = cur;
cur = next;
}
return pre;
}
}
class Node{
int value;
Node next;
public Node(int value) {
super();
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}