0

This is homework for school. I have a struct Employee that looks like this

typedef struct TEmployee
{
    struct TEmployee * m_Next;
    struct TEmployee * m_Bak;
    char * m_Name;
} TEMPLOYEE;

and a function to add a new employee that currently looks like this but I'm not sure how to make the m_Bak point to the previous employee

TEMPLOYEE * newEmployee(const char * name, TEMPLOYEE * next)
{
    TEMPLOYEE* head = NULL;
    head = malloc(sizeof(TEMPLOYEE));
    if(head==NULL)
    {
        return NULL;
    }

    head -> m_Name = strdup(name);
    head -> m_Next = next;
    head -> m_Bak = NULL;

    return head;
}

Any help is appreciated.

Lada1208
  • 57
  • 1
  • 5
  • "not sure how to make the m_Bak point to the previous employee" --> If `next` is not `NULL`, `next.m_Bak` points to the previous employee. For a good answer, we need to see how `newEmployee()` is called. – chux - Reinstate Monica Dec 30 '18 at 14:17

1 Answers1

0

If I understood correctly, try this:

TEMPLOYEE *newEmployee(const char *name, TEMPLOYEE *next)
{
  TEMPLOYEE *carry = (TEMPLOYEE *)malloc(sizeof(TEMPLOYEE));

  carry->m_Next = NULL;
  carry->m_Bak = NULL;
  carry->m_Name = (char *)malloc(sizeof(char) * strlen(name) + 1); // +1 for \0
  strcpy(carry->m_Name, name);

  if (next == NULL)
  {
    return carry;
  }
  else
  {
    carry->m_Next = next;
    return carry;
  }
}

When your *next is NULL it creates new start. When you add new Employee it prepends it to the start.

WutchZone
  • 154
  • 1
  • 3
  • 13