C 在尾部插入节点

C 在尾部插入节点,c,linked-list,C,Linked List,下面的代码将向列表的头部添加一个新节点。我想知道我将如何改变它,以便它将添加一个新的节点到列表的尾部(末端),而不是头部 typedef struct node{ int data; struct node *next; struct node *prev; } Node, *NodePtr; typedef struct linkedlist{ NodePtr head; NodePtr tail; } LinkedList, *LinkedListPtr; void insertTail

下面的代码将向列表的头部添加一个新节点。我想知道我将如何改变它,以便它将添加一个新的节点到列表的尾部(末端),而不是头部

typedef struct node{
int data;
struct node *next;
struct node *prev;
} Node, *NodePtr;

typedef struct linkedlist{
NodePtr head;
NodePtr tail;
} LinkedList, *LinkedListPtr;

void insertTail(LinkedListPtr list, int data){
NodePtr newNode;
newNode = (NodePtr)malloc(sizeof(Node));

newNode->data = data;
newNode->next =NULL;
newNode->prev =NULL;


/* add it to the beginning of linked list*/
if  (list->head==NULL){ /*linked list is empty*/
    list->head=newNode;
    list->tail=newNode;
}
else {
    //connect new node to the head of the list
    newNode->next = list->head;
    list->head->prev=newNode;

    //reassign head of the list
    list->head = newNode; 
}
}

您的列表是双重链接的,并且包含指向最后一个节点的指针,它应该是微不足道的。只需执行与头部插入相反的操作。您已经有一个指针
list->tail
。我建议你画一张图,告诉自己哪些指针必须设置为什么(比如:什么应该列表->尾部,新节点->上一个,新节点->下一个…指向),然后再试一次。算出了,谢谢大家。Gratulations,应该是这样的