您的位置:首页 > 编程语言 > Java开发

java链表反转

2016-12-08 17:10 375 查看
这里只实现遍历反转,还有一种递归反转这里未实现

/**
* 链表反转
* @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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java链表反转