7. 从尾到头打印链表
题目:
输入一个链表的头结点,从尾到头反过来打印出每个节点的值
注:
在做着道题之前,我先把我用java实现链表的代码贴出来(只简单的实现了增删改查,复杂的自己写):
import java.util.ArrayList;
import java.util.List;
/**
* Class Node ...
*
* @author LiJun
* Created on 2018/12/22
*/
public class Node<T> {
/**
* 假设我们的链表有头结点
*/
public T data;
public Node<T> next;
public Node(T data) {
this.data = data;
this.next = null;
}
public Node<T> addInTail(T data) {
Node<T> node = new Node<>(data);
if(this == null){
return node;
}
Node<T> p = this;
while (p.next != null) {
p = p.next;
}
p.next = node;
return this;
}
public Node<T> addInHead(T data) {
Node<T> node = new Node<>(data);
node.next = this;
return node;
}
public Node<T> delete(int index) {
Node<T> p = this;
if(index == 1){
return this.next;
}
int i = 0;
while (p.next != null) {
if (index-1 == i++) {
// 删除操作
p.next = p.next.next;
}
p = p.next;
}
return this;
}
public T select(int index) {
Node<T> p = this;
while (index-- > 1 && p != null) {
p = p.next;
}
if (p == null) {
return null;
}
return p.data;
}
public void update(int index, T data) {
Node<T> p = this;
while (index-- > 1 && p != null) {
p = p.next;
}
if (p != null) {
p.data = data;
}
}
@Override
public String toString() {
List<T> list = new ArrayList<>();
Node<T> p = this;
while (p != null) {
list.add(p.data);
p = p.next;
}
return "Node{" + list + '}';
}
public static void main(String[] args) {
Node<Integer> head = new Node<Integer>(0);
head = head.addInHead(1);
head = head.addInTail(2);
head = head.addInHead(3);
head = head.addInTail(4);
System.out.println(head);
head = head.delete(1);
System.out.println(head);
System.out.println(head.select(2));
head.update(1, 6);
System.out.println(head);
}
}
分析:
-
我们可能会想到将这个链表反转了,再来打印,但是这个改变了这个链表的结构,不是上上选
-
利用一个辅助数组,遍历链表,然后将数据存到数组中去,最后我们反过来读取数组的值就行了
但是这种方法会浪费大量的空间,所以万不得已不能这样做
-
应用递归来打印链表
/** * Class day07 ... * * @author LiJun * Created on 2018/12/22 */ public class day07 { public static void print(Node head){ if(head != null) { if (head.next != null) { print(head.next); } System.out.print(head.data + " "); } } public static void main(String[] args) { Node<Integer> head = new Node<>(0); head = head.addInHead(1); head = head.addInHead(2); head = head.addInHead(3); head = head.addInHead(4); head = head.addInHead(5); head = head.addInHead(6); print(head); } }