2016-08-01 2 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); 
} 

내가

(20) 전 (70 = 데이터) 노드를 삽입하려고 출력 : 30,20,10

예상 출력 : 30,70,20, 10

+0

오직'main'을 읽지 만,'head' 변수가 업데이트 될 필요가 있기 때문에 주소 ('& head')를 넘기지 않고 목록의 첫 번째 항목 앞에 어떻게 삽입 할 수 있는지 보지 못합니다. – user3386109

답변

1

insert_before을 호출하면 지정된 노드가 머리 인 경우 새 노드가 새 머리가됩니다. 따라서 주소를 수정하려면 head의 주소를 전달해야합니다.

은 당신이 지금 당장해야하는 것은 다음과 같습니다

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

이 문제를 해결하려면이 insert_before에 매개 변수 head의 주소를 포함한다.

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; 
    } 
} 

다음과 같이 호출 : 당신은 전달 된 매개 변수 next_node는 다음 머리 전에 노드를 삽입한다 머리 경우 insert_before에서 한 가지 누락 맞아요 최선을 다하고 있습니다

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

그러나 주어진 노드가 머리가 아닌 경우에는 어떻게해야합니까? – oldDoctor

+0

@oldDoctor 예상대로 계속 작동합니다. 사실, 원래 코드는 주어진 노드가'head'가 아닌 한 작동합니다. 업데이트 된 함수에서 첫 번째 인수는 항상'head'의 주소이고 두 번째 인수는 전에 새 노드를 배치 할 노드입니다. – dbush

2

을 . 따라서 새로 추가 된 노드를 head으로 만들어야합니다.

+0

그러나 전달 된 매개 변수가 머리가 아닌 경우에는 어떻게해야합니까? – oldDoctor

관련 문제