C使用下一个和上一个指针创建链接列表

时间:2018-12-30 14:14:49

标签: c pointers struct linked-list

这是学校的作业。我有一个看起来像这样的struct Employee

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

和一个用于添加当前看起来像这样的新员工的函数,但是我不确定如何使m_Bak指向前一个员工

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;
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,请尝试以下操作:

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;
  }
}

当您的*next为NULL时,它将创建一个新的开始。当您添加新员工时,它将添加到开头。