Sort by

recency

|

720 Discussions

|

  • + 0 comments

    C Approach

    For Beginners

    Node* insert(Node *head,int data) {

    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
    Node *ptr = head ;
    new_node->data = data;
    new_node->next = NULL;
    if(head==NULL){
        return new_node;
    }
    while(ptr->next!=NULL){
        ptr = ptr->next;
    }
    ptr->next = new_node;
    return head;
    

    }

  • + 0 comments

    short and sweet

    def insert(self,head,data): 
    #Complete this method
    self.head = data
    print(data,'',end="")
    
  • + 0 comments

    Python 3 Solution; def insert(self,head,data): new_node = Node(data) if head is None: head = new_node else: current = head while current.next: current = current.next current.next = new_node return head

  • + 0 comments

    Simple JAVA approach

    public static Node insert(Node head,int data) {

        if(head==null){
            head = new Node(data);
        }
        else{
            Node start = head;
            while(start.next != null){
            start = start.next;
        }
    
        Node newNode = new Node(data);
        start.next = newNode;
        }
        return head;
    }
    
  • + 0 comments

    I was hoping for a golang option. C++ is good enough I suppose...

    Node* insert(Node *head,int data)
          {
              //Complete this method          
              Node *dummyNode = new Node(0);
              dummyNode->next = head;
              Node *newNode = new Node(data);
              Node *current = dummyNode;
              
              while (current->next != NULL) {
                current = current->next;
              }
              current->next = newNode;
              return dummyNode->next;
          }