為什麼代碼中既有head,也有tail,他們兩個是什麼關系,各起到什麼作用?求大神解釋
Lnode * difference( Lnode *list1, Lnode *list2 )
{
Lnode *head = NULL;
Lnode *tail = NULL;
Lnode *new_node;
Lnode *copy_node;
// walk through both lists, adding nodes as necessary
while ( list1 != NULL || list2 != NULL ) {
copy_node = NULL;
if ( list1 != NULL && list2 != NULL
&& list1->data == list2->data ) {
list1 = list1->next; // skip common nodes
list2 = list2->next;
}
else if ( list1 != NULL
&&( list2 == NULL || list1->data < list2->data )) {
copy_node = list1;
list1 = list1->next;
}
else if ( list2 != NULL
&&( list1 == NULL || list2->data < list1->data )) {
copy_node = list2;
list2 = list2->next;
}
if( copy_node != NULL ) {
new_node = (Lnode *)malloc(sizeof(Lnode));
new_node->data = copy_node->data;
if( head == NULL ) {
head = new_node;
}
else {
tail->next = new_node;
}
tail = new_node;
}
}
return head;
}
head是頭節點,找到第一個不同的節點時,head指向它,即這個節點就是新產生的鏈表(2個鏈表的不同節點組成)的頭節點
tail,是用來在鏈表尾插入新節點的