Skip to content

Commit 8d578c2

Browse files
committed
输入个链表的头结点,从尾到头反过来打印出每个结点的值
1 parent bec0196 commit 8d578c2

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/main/java/com/algorithm/study/demo/algorithm/Jianzhi02.java

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ public ListNode(int e, ListNode next){
2424
private int size=0;// 保存已含有的节点数
2525
private ListNode root;
2626
private ListNode last;
27+
28+
/**
29+
* 添加元素到链表头部
30+
* @param e
31+
*/
2732
public void addFirst(int e){
2833
ListNode first=root;
2934
ListNode listNode=new ListNode(e,null);
@@ -33,6 +38,11 @@ public void addFirst(int e){
3338
}
3439
size++;
3540
}
41+
42+
/**
43+
* 添加元素到链表末尾
44+
* @param e
45+
*/
3646
public void add(int e){
3747
ListNode temp=last;
3848
if (temp==null){
@@ -45,14 +55,18 @@ public void add(int e){
4555
}
4656
size++;
4757
}
58+
public int size(){
59+
return size;
60+
}
4861
/**
4962
* 从尾到头反过来打印出每个结点的值
5063
*/
5164
public void printListInverselyUsingIteration() {
5265
Stack<ListNode> stack=new Stack();
53-
while (root!=null){
54-
stack.push(root);
55-
root=root.next;
66+
ListNode tempNode=root;
67+
while (tempNode!=null){
68+
stack.push(tempNode);
69+
tempNode=tempNode.next;
5670
}
5771
ListNode temp=null;
5872
while (!stack.isEmpty()){
@@ -69,9 +83,8 @@ public static void main(String[] args) {
6983
listnode.add(3);
7084
listnode.add(2);
7185
listnode.add(1);
86+
System.out.println("size:"+listnode.size());
7287
listnode.printListInverselyUsingIteration();
73-
LinkedList linkedList=new LinkedList();
74-
linkedList.add(1);
7588

7689
}
7790
}

0 commit comments

Comments
 (0)