Inserting a node

A node can be added in three ways

  1. At the front of the linked list
  2. After a given node.
  3. At the end of the linked list.

Add a node at the front

ListNode * LinkedList::push(ListNode *head, int data) {
    ListNode *node = new ListNode(data);
    node->next = head;
    head = node;
    return head;
}

Add a node after a given node

void LinkedList::insertAfter(ListNode *prev, int data) {
    ListNode *node = new ListNode(data);
    node->next = prev->next;
    prev->next = node;
}

Add a node at the end

void LinkedList::append(ListNode *head, int data) {
    ListNode *tail = head;
    while (tail->next) {
        tail = tail->next;
    }

    ListNode *node = new ListNode(data);
    tail->next = node;
}

results matching ""

    No results matching ""