在尾部插入节点

时间:2014-09-26 14:26:48

标签: 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(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; 
}
}

0 个答案:

没有答案