想要制作删除第一个节点的链表功能

Vat*_*ato 1 c linked-list

这是我的代码.我做了三个函数来添加一个新节点,在另外两个节点之间插入一个新节点,一个删除,但我不知道如何删除第一个节点.我甚至都不知道.

#include <stdlib.h>
#include <stdio.h>

struct Node
{
    int data;   
    struct Node *next;  
};
void insert(Node* insertafter, Node* newNode);
void add(Node* llist,Node* newNode);
void deleteafter(Node *llist);
void deletefirts();
int main()
{ 
    struct Node *llist;
    struct Node *newNode;
    newNode = (Node*)malloc(sizeof(struct Node));
    newNode->data = 13;
    struct Node *newNode2;
    newNode2 = (Node*)malloc(sizeof(struct Node));
    newNode2->data = 14;
    llist = (Node*)malloc(sizeof(struct Node));
    llist->data = 10;
    llist->next = (Node*)malloc(sizeof(struct Node));
    llist->next->data = 15;
    llist->next->next = NULL;
    insert(llist,newNode);
    add(llist,newNode2);
    if(llist->next == NULL)
    printf("shecdoma");
    struct Node *cursor = llist;
    while (cursor != NULL) 
    {
        printf("%d\n", cursor->data);          
        cursor = cursor->next;
    } 
    system("pause");
    return 0;   
}            
void insert(Node* insertafter, Node *newNode)
{
     newNode->next = insertafter->next;
     insertafter->next = newNode;
}
void add(Node* llist,Node *newNode)
{
     if(llist->next == NULL)
     {
     llist->next = newNode;
     newNode->next = NULL;
     }
     else
     {
       while(llist->next != NULL)                   
       {  
          llist = llist->next; 
       }
       add(llist,newNode);
     }

void deleteafter(Node *llist)
{
 if(llist->next != NUll)   
 llist->next = llist->next->next;   
}
void deletefirst(); 
{
}
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 6

您可以使用以下内容:

void deletefirst (struct Node **head) {
    struct Node *tmp = *head;            // save old head for freeing.
    if (tmp == NULL) return;             // list empty? then do nothing.
    *head = tmp->next;                   // advance head to second node.
    free (tmp);                          // free old head.
}
Run Code Online (Sandbox Code Playgroud)

您将指针传递到头部,以便您可以更改它.删除第一个节点以外的节点不需要这个,但删除第一个节点.

您设置了一个指向头部的临时指针,以便释放它,然后将头部更改为指向下一个元素.然后你释放旧头并返回.