Make use of LinkedList append


  • 0
    N
    class Solution {
        public int[] countBits(int n) {
    
    		MyList a = new MyList();
    		MyList b = null;
    		a.add(0);
    		int count = 0;
    		while (count <= n) {
    			b = new MyList();
    			Node curr = a.head;
    			while (curr != null) {
    				b.add(1 + curr.val);
    				++count;
    				curr = curr.next;
    			}
    			a.append(b);
    		}
    
    		int[] c = new int[n + 1];
    		int i = 0;
    		Node curr = a.head;
    		while (i <= n) {
    			c[i++] = curr.val;
    			curr = curr.next;
    		}
    
    		return c;
    	}
    
    	class Node {
    		int val;
    		Node next = null;
    		public Node(int val) {
    			this.val = val;
    		}
    	}
    	class MyList {
    		Node head = null;
    		Node tail = null;
    		public MyList() {
    
    		}
    
    		public void add(int val) {
    			Node node = new Node(val);
    			if (tail == null)
    				head = tail = node;
    			else {
    				tail.next = node;
    				tail = node;
    			}
    		}
    
    		public void append(MyList list) {
    			tail.next = list.head;
    			tail = list.tail;
    		}
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.