在C中将节点添加到链接列表的末尾

时间:2021-03-29 07:17:05

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

我的代码是添加节点到头部,但我希望它们添加到尾部。我尝试将头指向下一个节点为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();

3 个解决方案

#1


3  

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;

#2


1  

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

#3


1  

// 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);

#1


3  

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;

#2


1  

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

#3


1  

// 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);