讲一下基本思想:
单向链表要想反向输出,而不借助临时变量,那就是栈这个数据结构->递归一下就出现了.
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.Objects;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
class Node {
private Integer data;
private Node next;
}
/**
* @author 陈英俊
* @date 2020/11/30 17:46
*/
public class SingleLinkedListDemo {
public static void main(String[] args) {
Node head = new Node(0, null);
for (int i = 0; i < 10; i++) {
initLinkedList(head, new Node(i, null));
}
Node tmp = head;
while (tmp != null) {
System.out.print(tmp.getData() + "->");
tmp = tmp.getNext();
}
System.out.println();
//单链表反向输出
printLinkedList(head);
}
/**
* 单向链表反向输出
*
* @param head 头结点
*/
private static void printLinkedList(Node head) {
if (!Objects.isNull(head.getNext())) {
printLinkedList(head.getNext());
}
System.out.print(head.getData() + "->");
return;
}
/**
* 链表新增结点(尾插法)
*
* @param head 头结点
* @param add 新增结点
*/
private static void initLinkedList(Node head,Node add) {
Node tmp = head.getNext();
Node var = head;
while (tmp != null) {
var = tmp;
tmp = tmp.getNext();
}
var.setNext(add);
}
}
- 输出结果:
0->1->2->3->4->5->6->7->8->9->10->
10->9->8->7->6->5->4->3->2->1->0->
Process finished with exit code 0
网友评论