node节点:
public class Node {
Node next;
Integer value;
public Node(Integer value) {
this.value = value;
}
public Node addNode(Integer value) {
Node node = new Node(value);
this.next = node;
return node;
}
public Node(Integer value, Node next) {
this.next = next;
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
@Override
public String toString() {
return "Node{" +
"next=" + next +
", value=" + value +
'}';
}
}
main函数:
Node node1 = new Node(1);
Node node2 = node1.addNode(2);
Node node3 = node2.addNode(3);
Node node4 = node3.addNode(4);
Node node5 = node4.addNode(5);
Node node6 = node5.addNode(6);
Node node7 = node6.addNode(7);
1、循环算法:
private Node reverseNode(Node node1) {
Node pre = null;
Node curr = node1;
Node next;
while (curr != null) {
next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
2、递归算法:
private Node reverseNode1(Node head) {
if(head==null || head.next==null){
return head;
}
Node result = reverseNode1(head.next);
head.next.next=head;
head.next=null;
return result;
}
浙公网安备 33010602011771号