2016-08-01 165 views
1

我試圖在給定節點之前插入一個節點。但我無法獲得所需的輸出。在雙向鏈表中給定節點之前插入一個節點

#include<stdio.h> 
#include<stdlib.h> 

struct node{ 

    int data; 
    struct node* prev; 
    struct node* next; 
}; 

void insert_beg(struct node** head, int new_data){ 
    struct node* temp = (struct node*)malloc(sizeof(struct node)); 
    temp->data = new_data; 

    if(*head == NULL){ 

     temp->next = *head; 
     temp->prev = NULL;   
     *head = temp; 
    } 
    else{ 
     temp->next = *head;  
     (*head)->prev = temp; 
     *head = temp; 
    } 
} 

void insert_before(struct node* next_node,int new_data){ 
    struct node* temp = (struct node*)malloc(sizeof(struct node)); 
    temp->data = new_data; 

    if(next_node == NULL) 
     printf("Invalid!!!!"); 


    temp->prev = next_node->prev; 
    temp->next = next_node; 
    next_node->prev = temp; 

    if(temp->prev!=NULL) 
     temp->prev->next = temp; 
} 

void printList(struct node* head){ 

    if(head == NULL) 
     printf("The list is empty\n"); 
    else 
     { 
      while(head!=NULL){ 

       printf("%d\n",head->data);    
       head = head->next;    
       } 
     } 
} 

int main(){ 

    struct node* head = NULL; 
    printList(head);  
    insert_beg(&head,10); 
    insert_beg(&head,20); 
    insert_before(head,70); 
    insert_beg(&head,30); 

    printList(head); 
} 

在這裏,我試圖插入的節點(與數據= 70)前20

輸出:30,20,10

預期輸出:30,70,20, 10

+0

只讀'main',但我沒有看到如何在列表中的第一項之前插入而不通過地址('&head'),因爲'head'變量需要更新。 – user3386109

回答

1

當您撥打insert_before時,如果給定節點是頭部,則新節點將成爲新頭部。所以你需要通過head的地址來修改它。

你現在看起來是這樣的:

head 
    | 
    v 
------   ------   ------ 
- 30 - ---> - 20 - ---> - 10 - 
------ <--- ------ <--- ------ 
       ^
------   | 
- 70 - ---------| 
------ 

爲了解決這個問題,包括head在參數insert_before地址。

void insert_before(struct node **head, struct node *next_node, int new_data){ 
    struct node* temp = malloc(sizeof(struct node)); // don't cast the return value of malloc 
    temp->data = new_data; 

    if(next_node == NULL) 
     printf("Invalid!!!!"); 


    temp->prev = next_node->prev; 
    temp->next = next_node; 
    next_node->prev = temp; 

    if(temp->prev!=NULL) { 
     temp->prev->next = temp; 
    } else { 
     *head = temp; 
    } 
} 

然後調用它像這樣:

insert_before(&head,head,70); 
+0

但是,如果給定的節點不是首腦? – oldDoctor

+0

@oldDoctor它仍將按預期工作。實際上,只要給定的節點不是「head」,你的原始代碼就會工作。在更新後的函數中,第一個參數總是「head」的地址,第二個參數是要放置新節點的節點。 – dbush

2

你正在做right.But你缺少一個東西在insert_before如果傳遞的參數next_node是頭,那麼你將被插入頭節點之前的一切。因此,您必須將此新添加的節點設爲head

+0

但是,如果傳遞的參數不是頭呢? – oldDoctor

相關問題