Morbidity
Morbidity

Reputation: 93

Adding nodes to end of a linked list in C

The code I have is adding nodes to head but I want them added to tail. I tried pointing head to next node to null but it stops since the next node is null

if(head==NULL)
{
    head=node;
}
else
{
    node->next=head;
    node->prev=NULL;
    head->prev=node;
    head=node;
}
printf("The node is inserted to linked list succesfully. \n\n");
printMenu();

Upvotes: 0

Views: 3309

Answers (3)

rainman
rainman

Reputation: 121

// Create new node
struct nodeType *newNode = (struct nodeType *)malloc(sizeof(struct nodeType));

// Singly-linked list and new node is end of the list so the next pointer is NULL
newNode->next = NULL;

if(head==NULL){
    // If head is not assigned
    head = newNode;
}
else{
    // Assign the next pointer in the current node to the new node
    current->next = newNode;
}
// Update the current pointer to point to the newNode
current = newNode;

where head and current is,

struct nodeType *head, *current;

If the current pointer does not point to the end of the list you can iterate over the list to the end with the following line and then start appending to the linked-list:

for(current = head; current->next != NULL; current = current->next);

Upvotes: 1

Rob
Rob

Reputation: 3381

You need to go to the end of the list first:

if(head==NULL)
{
    head=node;
}
else
{
  struct nodetype *p = head;
  while (p->next)
    p = p->next;
  p->next = node;
  node->prev = p;
}

Upvotes: 1

3yakuya
3yakuya

Reputation: 2672

You need to keep a pointer to your list's tail, and then adding an element may look like:

node -> next = NULL;
tail -> next = node;
node -> prev = tail;
tail = node;

Upvotes: 3

Related Questions