Insert an element in a sorted linked list


  • 0
    W
    struct ListNode {
          int val;
          struct ListNode *next;
     };
    
    struct ListNode * Insert(struct ListNode *head, struct ListNode *element) {
         struct ListNode *p=head;
         int data;
         if(!head) return element;
    
         while(p){
              if(p->val <= element->val) p=p->next;
              else { // p is greater than element
                      /* insert element before p */
                      element->next = p->next; // insert element after p first then swap p and element
                      p->next = element;
                      data = p->val;
                      p->val = element->val;
                      element->val = data;
                      break;
              }       
         }
         return head;
    }
    // insert an head node to make it easier 
    struct ListNode * Insert(struct ListNode *head, struct ListNode *element) {
         struct ListNode *p,*headl;
          headl = (struct ListNode *)malloc(sizeof(ListNode));
          headl -> next = head;
         if(!head) return element;
    
         while(p->next){
              if(p->next->val <= element->val) p=p->next;
              else { // p->next is greater than element
                      /* insert element after p */
                      element->next = p->next;
                      p->next = element;
                      break;
              }       
         }
        return headl->next;
    }
    

Log in to reply
 

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