删除单个链表中的元素

时间:2011-05-05 05:46:28

标签: c

  

可能重复:
  delete elements in a singular linked list

在此代码中我将删除链表中的元素

11-> 12-> 13-> 14-> 15-> 12-> 16

如果我删除11我得到一个分段错误逻辑中的错误 谁能给我一些投入?

#include<stdio.h>
#include<stdlib.h>
void insertbeg();
void delpos();
void display();

struct node
{
    int info;
    struct node *link;
}*first=NULL;

struct node *create();
int item,key;
main()
{
    int choice;
    while(1)
    {
        printf("\nchoices are:\n");
        printf("\n1.Insertbeg\n 2.delpos\n 3.display\n 4.exit\n");
        printf("Enter U'r choice: ");
        scanf("%d",&choice);
        switch(choice)
        {
            case 1: insertbeg(); break;
            case 2: delpos(); break;
            case 3: display(); break;
            case 4: exit(1);
            default: printf("INVALID CHOICE TRY AGAIN\n");
        }
    }
}

struct node *create()
{
    struct node *new;
    new=(struct node*)malloc(sizeof(struct node));
    return(new);
}

void insertbeg()
{
    struct node *new;
    new=create();
    printf("Enter element to be inserted: ");
    scanf("%d",&item);
    if(first==NULL)
    {
        new->info=item;
        new->link=NULL;
        first=new;
    }
    else
    {
        new->info=item;
        new->link=first;
        first=new;
    }
}

void delpos()
{
    int key;
    struct node *temp,*prev;
    if(first==NULL)
    {
        printf("LIST IS EMPTY\n");
        return;
    }
    else
    {
        temp=first;
        printf("Enter the KEY element which is to be deleted: ");
        scanf("%d",&key);
        while(temp->info!=key&&temp->link!=NULL)
        {
            prev=temp;
            temp=temp->link;
        }
        if(temp->info==key)
        {
            prev->link=temp->link;
            free(temp);
        }
        else
            printf("key element not found in the list\n");



    }
}

void display()
{
    struct node *temp;
    temp=first;
    if(temp==NULL)
    {
        printf("LIST IS EMPTY\n");
        return;
    }
    else
    {
        printf("Elements in Linked Lists: ");       

        while(temp!=NULL)
        {
            printf("%d->",temp->info);
            temp=temp->link;
        }
    }
}

0 个答案:

没有答案