完整代码及详细的注释如下:
package com.dhasa.test;
/**
* @company dhasa
* @author dl
*
*/
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.addNode(5);
ll.addNode(4);
ll.addNode(3);
ll.addNode(2);
ll.addNode(1);
ll.addNode(0);
ll.print(ll.getHead());
// System.out.println("\n------反转链表之后的输出结果------");
// ll.print(ll.reverseLinkedList(ll.getHead()));
System.out.println("\n------反转链表之后的输出结果------");
ll.print(ll.reverse(ll.getHead()));
}
}
class LinkedList{
//头结点
private Node head = null;
//get set方法获取头结点
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
/**
* 内部类node
* @author dl
*/
private class Node{
private Node next;
private Object obj;
public Node(Object obj){
this.obj = obj;
this.next = null;
}
}
/**
* 头插法
* @author dl
*/
public void addNode(Object obj){
Node node = new Node(obj);
node.next = head;
head = node;
}
/**
* 打印链表
* @author dl
*/
public void print(Node current){
while(current!=null){
System.out.print(current.obj+"->");
current = current.next;
}
}
/**
* 反转链表(循环):
* 0、对当前节点进行判断:当前节点或者其next为空,则可以直接返回。(如果为空,则直接返回null的preNode)
* 1、先保存当前节点的后续节点(nextNode),否则丢失后续节点无法反转链表
* 2、将当前节点(current)指向先前节点preNode;
* 3、将当前节点(current)变为先前节点(preNode)
* 4、将之前保存的后续节点(nextNode)变为当前节点继续循环
* @author dl
*/
public Node reverseLinkedList(Node current){
/**不必要的部分**/
// if(null==current||null==current.next){
// return current;
// }
Node nextNode = null;
Node preNode = null;
while(current!=null){
nextNode = current.next;
current.next = preNode;
preNode = current;
current = nextNode;
}
return preNode;//最终current变为null时结束循环,因此返回的preNode为最终的头结点(但head引用依然没变)
}
/**
* 反转链表(递归)
* @author dl
* 0、对当前节点进行判断:当前节点或者其next为空,则可以直接返回。
* 1、每次调用,先保存当前节点的后续节点(nextNode),然后将当前节点的next设置为null(则可以看到一个一个next被置空的单独的节点)
* 2、依次调用自身,直到最后一个节点返回。
* 3、每次循环的后一个节点指向当前节点(nextNode->current)
* 4、最终返回新的第一个节点,也就是循环的出口---旧的最后一个节点
*/
public Node reverse(Node current){
if(null==current || null==current.next){
return current;
}
Node nextNode = current.next;
current.next = null;
Node reverseBack = reverse(nextNode);
nextNode.next = current;
return reverseBack;
}
}