2016-04-11 46 views
0

我在合併2列表中有問題,所以我(想)在做什麼。將列表A分配給當前,去往當前節點,將列表B添加到當前,給head2分配電流,最後打印。但是當我運行它沒有一出來,HEAD2列表中仍然空合併兩個鏈表

#include<stdio.h> 
#include<stdlib.h> 
typedef struct node { 
int val; 
struct node * next; 
} node_t; 

void print_list(node_t * head); 
node_t* merge(node_t *head,node_t *head1); 

int main(){ 
int number; 
node_t * head = NULL; 
node_t * head1 = NULL; 

//inputA 
//inputB 

printf("merged list is : \n"); 
print_list(merge(head,head1)); 
printf("\n"); 
return 0; 
} 

node_t *merge(node_t *head,node_t *head1){ 
    node_t * current = head; 
    while(current->next != NULL){ 
    current = current->next; 
    } 
    current->next = head1; 
    return current;  
} 
void print_list(node_t * head) { 
node_t * current = head; 

while (current != NULL) { 
    printf("%d ", current->val); 
    current = current->next; 
    } 
} 

編輯:頭部名單A和頭像1是名單B,已經有一些數據。它只會保留A ex的最後一個節點。 A = 1 2 3,B = 4 5 6返回3個4 5 6

+0

我建議'HEAD2 =合併(頭,頭像1); ..''在merge':'返回頭;' – BLUEPIXY

+0

我的方法是錯誤的,我如何保持雙方名單? – Hary

+0

創建結果的新列表(每個元素)。 – BLUEPIXY

回答

0

兩個問題:

合併正在經過HEAD2的副本,所以在主的HEAD2不會改變。您需要將指針傳遞給head2。

void merge(struct node *head,struct node *head1,struct node **head2) 
{ 
    //the merge is ok, but the beginning of the list 
    //is head not head1 

    // dereference the pointer to head2 to change 
    // the value of head2 in main. 
    *head2 = head; 
} 

此外,這是一個真正的追加操作而不是合併。

+0

是的,我錯了,這不是合併。如何做一個? – Hary

0

我看到合併問題:
*如果左頭是NULL,則會發生segfault。
*它返回合併點,而不是真正的新共同頭。

node_t *merge(node_t *head,node_t *head1){ 
    if (head == NULL) 
     return head1; 
    node_t * current = head; 
    while(current->next != NULL){ 
    current = current->next; 
    } 
    current->next = head1; 
    return head; 
}