java从尾到头打印链表数据_【6. 从尾到头打印链表】剑指offer-JAVA实现

题目描述: 从尾到头反过来打印出每个结点的值。

思路1:头插法

代码:

public class Six {

private Node first;

public class Node{

public int key;

public Node next;

}

public Node createN(Node head) {

Scanner in = new Scanner(System.in);

while(in.hasNext()) {

if(head==null) {

head = new Node();

head.key = in.nextInt() ;

head.next = null;

}else {

Node newNode = new Node();

newNode.key = in.nextInt();

newNode.next = head;

head=newNode;

}

}

return head;

}

public void printNode(Node n) {

if(n==null)

System.out.println("空链表");

while(n!=null) {

System.out.println(n.key);

n = n.next;

}

}

}

思路2: 后进先出想到栈, 把链表放进栈中/尾插+扔进栈中在拿出来

代码:

Stack s = new Stack<>();

public class Node{

public int key;

public Node next;

}

public Node createN(Node head,Node tailer) {

Scanner in = new Scanner(System.in);

while(in.hasNext()) {

if(head==null) {

head = new Node();

head.key = in.nextInt();

head.next = null;

tailer = head;

}else {

Node newNode = new Node();

newNode.key = in.nextInt();

tailer.next = newNode;

tailer = newNode;

}

}

return head;

}

public void printN(Node head) {

Stack s = new Stack<>();

while(head!=null) {

s.add(head.key);

head=head.next;

}

Stack o = new Stack<>();

while(!s.isEmpty())

o.add(s.pop());

Iterator it = o.iterator();

while(it.hasNext())

System.out.println(it.next());

}

}

复制代码

总结: 1.头插法:

newNode.next = head;

head=newNode;

2.尾插法

tailer.next = newNode;

tailer = newNode;

3.递归本质是栈结构

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值