删除链表中的随机节点

时间:2011-04-20 07:03:03

标签: c

我写了这段代码来删除链表中的任何项目,

this is the output after insertion
 16 -->  15 -->  14 -->  13 -->  12 -->  11 --> 

when i delete 11 the output is like this
16 -->  15 -->  14 -->  13 -->  12 -->  0 --> 

如何在最后删除零?

typedef struct node
{
int data;
struct node *next;
}node;

node *getnode()
{
node *x;
x = (node*)malloc(sizeof(node));
if (x==NULL)
    {
        printf("no memory \n");
        exit(1);
    }
return x;
}

node *insert_front(int item , node *first)
{

node *temp;
temp = first;

temp = getnode();
temp -> data = item;
temp -> next = first;
return temp;
}

void *display(node *first)
{
node *temp;
temp = first;
if (temp == NULL)
    {
        printf("list is empty \n");
        return ;
    }
while (temp != NULL)

    {
        printf(" %d --> ",temp -> data);
        temp = temp -> next;

    }
}


void delete_middle(int item, node *first)
{
node *temp;
node *store_addr;
int value;
temp = first;
if (temp == NULL)
{
   printf("list is empty \n");
   return ;
}

while(temp!=NULL)
{
if (temp->data == item)
{
    if(temp->next != NULL)
    {
    temp->data =  temp->next->data;
            temp->next = temp->next->next;
    }
    else
     free(temp); 
    break;
}
temp = temp->next;
}


}


main()
{

node *first;
int item = 11,ch,i;
first = NULL;
while(1)
{
    printf("\n 1.insert front \n 2.display \n 3. delete middle \n 4.quit\n");
            scanf ("%d",&ch);
    switch(ch)
    {

    case 1:  // printf("\nenter the item to be inserted \n");
          //scanf("%d",&item);
           for(i=0 ;i<6;i++)
          first = insert_front (item++ , first);
          break;

    case 2:   display(first);
          break;


    case 3 :  printf("delete in middle \n");
          scanf("%d",&item);
          delete_middle(item, first);
          break;

    case 4:   exit(0);
          break;
}
}
}

2 个答案:

答案 0 :(得分:3)

删除时,必须将上一个节点存储在列表中并进行修改。 例如,您可以单独处理第一个节点并像这样循环

struct node* tmp;    
while(temp->next!=NULL)
{
    if (temp->next->data == item)
    {
        tmp = temp->next->next;
        free(temp->next); 
        temp->next = tmp;
    }
    temp = temp->next;
}

在您的代码中,如果是最后一个,则释放(temp),但不要将其从列表中删除。这会使列表损坏,并可能导致软件的许多不良行为。永远不要保留对释放指针的引用。

答案 1 :(得分:0)

在你的代码中试试这个,

while(temp!=NULL)
{
   if (temp->data == item)
   {
        if(temp->next != NULL)
        {
            prev->next = temp->next;
        }

        free(temp);
        break; 
   } 
   prev = temp;
   temp = temp->next; 
 }