我的代码是添加节点到头部,但我想将它们添加到尾部。我尝试将头指向下一个节点为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();
答案 0 :(得分:3)
你需要保持指向列表尾部的指针,然后添加一个元素可能如下所示:
node -> next = NULL;
tail -> next = node;
node -> prev = tail;
tail = node;
答案 1 :(得分:1)
您需要先到列表的末尾:
if(head==NULL)
{
head=node;
}
else
{
struct nodetype *p = head;
while (p->next)
p = p->next;
p->next = node;
node->prev = p;
}
答案 2 :(得分: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;
头部和电流在哪里,
struct nodeType *head, *current;
如果当前指针未指向列表的末尾,您可以使用以下行迭代列表到末尾,然后开始追加到链接列表:
for(current = head; current->next != NULL; current = current->next);