链表基础

一、新建链表

class Link{  
    private Node root;  
      
    class Node{  
       private String name;  
       private Node Next;  
       public Node(String name){  
           this.name = name;  
       }  
       public String getName(){  
           return this.name;  
       }  
       public void addNode(Node newNode){  
           if(this.Next==null){  
               this.Next = newNode;  
           }else{  
               this.Next.addNode(newNode);  
           }  
       }  
       public void printNode(){  
           System.out.print(this.name + "-->");  
           if(this.Next!=null){  
               this.Next.printNode();  
           }  
       }  
    };  
    public void add(String name){  
        Node newNode = new Node(name);  
        if(this.root==null){  
            this.root = newNode;  
        }else{  
            this.root.addNode(newNode);  
        }  
    }  
    public void print(){  
        if(this.root!=null){  
            this.root.printNode();  
        }  
    }  
};  
  
public class LinkDemo {  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
          Link link = new Link();  
          link.add("根节点");  
          link.add("第一节点");  
          link.add("第二节点");  
          link.add("第三节点");  
          link.add("第四节点");  
          link.print();  
          System.out.println("null");  
            
    }  
  
}  
链接:http://blog.csdn.net/chichoxian/article/details/8549744

二、 输入一个链表,从尾到头打印链表每个节点的值。

import java.util.Stack;
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
 
        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        return list;       
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值