/**
* 通过迭代、递归实现连表反转
* @author :彭先生
*/
public class ChainReverse {
@Data
static class ChainNode{
private String value;
private ChainNode next;
public ChainNode(String value, ChainNode next){
this.value = value;
this.next = next;
}
}
/**
* 迭代方式实现
* @return
*/
public static ChainNode iteration(ChainNode chainNode){
//保存链边下一个指针
ChainNode nextNode;
//保存下一个节点的上一个指针
ChainNode prevNode = null;
//保存需要进行遍历的链表节点
ChainNode thisNode = chainNode;
while (thisNode != null) {
nextNode = thisNode.next;
thisNode.next = prevNode;
prevNode = thisNode;
thisNode = nextNode;
}
return prevNode;
}
/**
* 递归方式实现
* @return
*/
public static ChainNode recursion(ChainNode chainNode){
if(chainNode.next == null){
return chainNode;
}
ChainNode recursion = recursion(chainNode.next);
chainNode.next.next = chainNode;
chainNode.next = null;
return recursion;
}
public static void main(String[] args) {
ChainNode chainNode1 = new ChainNode("1", null);
ChainNode chainNode2 = new ChainNode("2", chainNode1);
ChainNode chainNode3 = new ChainNode("3", chainNode2);
ChainNode chainNode4 = new ChainNode("4", chainNode3);
ChainNode chainNode5 = new ChainNode("5", chainNode4);
/* 反转前默认是:5--->4--->3--->2--->1--->null */
System.out.println("链表反转前:" + chainNode5);
/* 迭代反转后是:1--->2--->3--->4--->5--->null */
ChainNode iteration = iteration(chainNode5);
System.out.println("使用迭代方式实现链表反转后:" + iteration);
/* 递归再次反转后是:5--->4--->3--->2--->1--->null */
ChainNode recursion = recursion(iteration);
System.out.println("使用递归方式实现链表反转后:" + recursion);
}
}
分别通过迭代和递归算法实现链表反转
最新推荐文章于 2024-07-25 22:14:03 发布