Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 删除线性单链表中给定列表开头的节点_C_Algorithm - Fatal编程技术网

C 删除线性单链表中给定列表开头的节点

C 删除线性单链表中给定列表开头的节点,c,algorithm,C,Algorithm,我有下面的代码,它从线性单链表中删除给定的节点。 我想知道我们是否仍然可以改进这个程序,它是否随时中断 struct node { int num; struct node *next; } ; typedef struct node s; void delete(struct node *first) { int flag = 0; s *ptr, *lastNodePt

我有下面的代码,它从线性单链表中删除给定的节点。 我想知道我们是否仍然可以改进这个程序,它是否随时中断

   struct node
    {
      int num;
      struct node *next;
    } ;


   typedef struct node s;

    void delete(struct node *first)
     {
            int flag = 0;
            s *ptr, *lastNodePtr = NULL, *deleteNode;
            deleteNode = (s*) malloc(sizeof(s));
            printf("enter the node value to delete");
            scanf_s("%d",&deleteNode->num);
            deleteNode->next = NULL;

            for (ptr=first;ptr!=NULL;ptr=ptr->next) //at least one element exist
            {
              if(deleteNode->num == ptr->num)
              {
                flag=1;
                if(ptr==first) //need to delete at first place
                {
                  free(ptr);
                  first = null; //i dont think we need to do this as it points to ptr and ptr is already null.
                }
                else // need to delete some where middle.it can be last as well.
                {
                  lastNodePtr->next=ptr->next;
                  free(ptr);
                }

                printf("successfully deleted..");
                break;
              }

              lastNodePtr=ptr; // taking note of last node visited..
            }

            if (flag==0)
            {
              printf("\n Couldn't find the node");
              return;
            }
      }

如果ptr是列表中要删除的第一个元素,则将first设置为null,而不是ptr的下一个。(副作用:您无法释放列表的其余部分)

您的EDITH:delete应该返回新的Head,最好将其设置为struct node**first参数,如果第一个元素是已删除的元素,则该参数会更改第一个元素

顺便说一句:永远不要抛出malloc的结果

顺便说一句,两个。为什么使用for循环?每个人都使用链接列表的while循环

顺便说一句:链表的常规变量名是“head”、“list”、“next”、“prev”、“last”,它们都是相同的长度,因此排列整齐

struct node
{
  struct node *next;
  int num;
} ;

void delete(struct node **pp, int num) {
    struct node *del;

    for (   ;*pp; pp= &(*pp)->next) {
        if((*pp)->num == num) break;
        }

    if (!*pp) { printf("Couldn't find the node(%d)\n", num); return; }

    del = *pp;
    *pp = del->next;
    free(del);
  }
顺便说一句:
for()
循环没有错;它们允许您将所有循环逻辑放在一行。

结构节点*s”和“s*last”是一个太多的指针