File tree Expand file tree Collapse file tree
src/main/java/com/algorithm/study/demo/algorithm Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .algorithm .study .demo .algorithm ;
2+
3+ import java .util .Stack ;
4+
5+ /**
6+ *
7+ * 输入个链表的头结点,从尾到头反过来打印出每个结点的值
8+ *
9+ **/
10+
11+ public class Jianzhi02 {
12+
13+ public static class ListNode {
14+ int val ;
15+ ListNode next ;
16+
17+ public ListNode (int e , ListNode next ){
18+ this .val =e ;
19+ this .next =next ;
20+ }
21+ }
22+ private int size =0 ;// 保存已含有的节点数
23+ private ListNode root ;
24+ public void addFirst (int e ){
25+ root =new ListNode (e ,root );
26+ size ++;
27+ }
28+
29+ /**
30+ * 从尾到头反过来打印出每个结点的值
31+ */
32+ public void printListInverselyUsingIteration () {
33+ Stack <ListNode > stack =new Stack ();
34+ while (root !=null ){
35+ stack .push (root );
36+ root =root .next ;
37+ }
38+ ListNode temp =null ;
39+ while (!stack .isEmpty ()){
40+ temp =stack .pop ();
41+ System .out .println (temp .val );
42+ }
43+
44+ }
45+
46+
47+ public static void main (String [] args ) {
48+ Jianzhi02 listnode =new Jianzhi02 ();
49+ listnode .addFirst (4 );
50+ listnode .addFirst (3 );
51+ listnode .addFirst (2 );
52+ listnode .addFirst (1 );
53+ listnode .printListInverselyUsingIteration ();
54+
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments