【问题标题】:Inserting a node before a given node in doubly linked list在双向链表中的给定节点之前插入一个节点
【发布时间】:2016-08-01 19:33:44
【问题描述】:

我试图在给定节点之前插入一个节点。但我无法获得所需的输出。

#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

【问题讨论】:

  • 只读取main,但我看不出如何在不传递地址(&amp;head)的情况下在列表中的第一项之前插入,因为head 变量将需要更新。

标签: c linked-list


【解决方案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);

【讨论】:

  • 但是如果给定的节点不是头呢?
  • @oldDoctor 它仍将按预期工作。实际上,只要给定节点不是head,您的原始代码就可以工作。在更新后的函数中,第一个参数始终是head的地址,第二个参数是要放置新节点之前的节点。
【解决方案2】:

您做的一切都是正确的。但是您缺少一件事在insert_before 中,如果传递的参数next_node 是head,那么您将在head 之前插入一个节点。因此,您必须将这个新添加的节点设为head

【讨论】:

  • 但是如果传入的参数不是head呢?
猜你喜欢
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2021-08-02
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多