這裏只實現遍歷反轉,還有一種遞歸反轉這裏未實現
/**
* 鏈表反轉
* @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;
}
}