简体   繁体   中英

How Do I Fix This Sorted Linked List Insertion?

I was given an simple assignment that deals with doubly linked lists, dynamic data allocation, and recursion. I created an array of just 10 integers and I am trying to put these integers into a sorted doubly linked list using recursion. I am having some trouble with inserting nodes into the linked list; my output is "2 7 9 100" and is missing the other 6 integers for some reason. What am I doing wrong? Thank you for any help! (The language used is C)

#include <stdio.h>

#include <stdlib.h>

#define N 10

typedef struct node_ {
  int value;
  struct node_ *next;
  struct node_ *prev;
} node;

void insert(node **head, node *cur, node *p);
void print_list(node *cur);


void print_list(node *cur)
{
  if (!cur) {
    printf("\n");
    return;
  } else {
    printf("%d ", cur->value);
    print_list(cur->next);
  }
}

int main(int argc, char *argv[])
{
  int i;
  int data[N] = {2, 7, 3, 9, 4, 4, 0, 8, 7, 100};
  node *p, *head;
  head = NULL;
  for (i = 0; i < N; i++) {
    p = (node *)malloc(sizeof(node));
    p->value = data[i];
    insert(&head, head, p);
  }

  print_list(head);
}

void insert(node **head, node *cur, node *p)
{
  if(*head == NULL) 
  {
     p->next = p->prev = NULL;
    *head = p;
    return; 
  }
  if(p->value < cur->value)
  {
    p->prev = cur->prev;
    p->next = cur;
    cur->prev = p;
    if(cur->prev != NULL) 
      cur->prev->next = p;
    else
      *head = p; 
    return; 
  }
  if(cur->next == NULL) 
  {
    cur->next = p;
    p->next = NULL;
    p->prev = cur;
  }
  else 
    insert(head, cur->next, p);
}

I believe the problem is here:

cur->prev = p;
if(cur->prev != NULL) 

That if is never going to be false since you already lost the value of cur->prev .

You need to save cur->prev into a temporary variable and use that in the if statement, or do the assignment after the if.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM