删除双向链表中的第n个节点

时间:2017-08-07 15:31:48

标签: c data-structures linked-list

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct node
{
  int data;
  struct node *prev;
  struct node *next;
};
struct node* HEAD;
void Deleteatn(int c)
{
  struct node *store,*store1,*temp=HEAD;
  if(c==1)
  {
    store=temp->next;
    store->prev=NULL;
    HEAD=store;
    free(temp);
  }

  else
  {
   for(int i=1;i<c-1;i++)
      temp=temp->next;

   store=temp->next;
   store1=store->next;
   temp->next=store->next;
   //store1->prev=temp;//DOUBT
   free(store);
  }
}
void print()
{
  struct node *temp=HEAD;
  while(temp!=NULL)
  {
    printf("%d ",temp->data);
    temp=temp->next;
  }
  printf("\n");
}
void Insertatend(int b)
{
  struct node *n;
  n=(struct node *)malloc(sizeof(struct node));
  n->data=b;
  n->prev=NULL;
  n->next=NULL;
  if(HEAD==NULL)
    HEAD=n;
  else
  {
    struct node *store,*temp=HEAD;
    while(temp!=NULL)
       {
        store=temp;
        temp=temp->next;
       }
       store->next=n;
       n->prev=store;
  }
}
int main()
{
    int a,b,c;
    printf("How many Numbers need to be inserted?\n");
    scanf("%d",&a);
    for(int i=0;i<a;i++)
     {
      printf("Enter a number\n");
      scanf("%d",&b);
      Insertatend(b);
     }
     printf("The List is\n");
     print();
     printf("Enter which node need to be deleted?\n");
     scanf("%d",&c);
     Deleteatn(c);
     printf("The List After Deletion is\n");
     print();
     return 0;
}

这里我编写了一个删除双向链表中第n个节点的程序,我怀疑如果没有后向链接,输出如何正确。所以在双向链表中是不是强制要求前进和后退链接?

我已经提到代码行有疑问,没有那段代码,它是如何工作的?

1 个答案:

答案 0 :(得分:2)

您可以在追溯时找到问题。 由于你正在向前移动它的工作正常,就像一个单独的链表。