【6. 從尾到頭打印鏈表】劍指offer-JAVA實現

題目描述: 從尾到頭反過來打印出每一個結點的值。code

思路1:頭插法遞歸

代碼:it

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: 後進先出想到棧, 把鏈表放進棧中/尾插+扔進棧中在拿出來class

代碼:鏈表

Stack<Integer> 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<Integer> s = new Stack<>();
            while(head!=null) {
                s.add(head.key);
                head=head.next;
            }
            Stack<Integer> 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.尾插法next

tailer.next = newNode;
       tailer = newNode;

3.遞歸本質是棧結構while

相關文章
相關標籤/搜索