Adding items to end of linked list

后端 未结 9 855
夕颜
夕颜 2020-12-03 16:03

I\'m studying for an exam, and this is a problem from an old test:

We have a singly linked list with a list head with the following declaration:

clas         


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 16:56

    class Node {
        Object data;
        Node next;
        Node(Object d,Node n) {
            data = d ;
            next = n ;
           }
    
       public static Node addLast(Node header, Object x) {
           // save the reference to the header so we can return it.
           Node ret = header;
    
           // check base case, header is null.
           if (header == null) {
               return new Node(x, null);
           }
    
           // loop until we find the end of the list
           while ((header.next != null)) {
               header = header.next;
           }
    
           // set the new node to the Object x, next will be null.
           header.next = new Node(x, null);
           return ret;
       }
    }
    

提交回复
热议问题