The last question of the PTA function: delete nodes from the linked list

Delete the node in the linked list
(the first time I write, it is a bit unwieldy to type)
the code above:
#include <stdio.h>
#include <stdlib.h>

struct ListNode {//define linked list
int data;
struct ListNode* next;
};

struct ListNode* readlist();
struct ListNode* deletem(struct ListNode* L, int m);
void printlist(struct ListNode* L)//输出
{
struct ListNode* p = L;
while § {
printf("%d “, p->data);
p = p->next;
}
printf(”\n");
}

int main()
{
int m;
struct ListNode* L = readlist();
scanf("%d", &m);
L = deletem(L, m);
printlist(L);

return 0;

}
struct ListNode* readlist()
{ struct ListNode* head, * tail, * p; head = tail = NULL;//head is empty for judging the initial value, tail is zero for the end of the linked list while (1) { p = ( struct ListNode*)malloc(sizeof(struct ListNode)); scanf("%d", &(p->data));





    if (p->data < 0)//输入小于零时结束
        break;
    p->next = NULL;//由于链表顺序与插入顺序相同,故每读入一项都要使下一项指向空
    if (head == NULL)//对链表赋初值(头节点)
        head = p;
    else tail->next = p;//将链表读入
    tail = p;//尾指针后移
}
return head;

}
struct ListNode* deletem(struct ListNode* L, int m)
{ struct ListNode* p, * q; //p is the previous node to be deleted, q is the node to be deleted while (L != NULL && L->data == m) //When the linked list is not empty, judge whether the head node of the linked list is the element to be deleted { q = L; L = L->next; free(q); } if (L == NULL) // Determine whether the linked list is empty { return NULL; }










//删除头结点后指定的结点
p = L;                //p为要删除结点的前一结点
q = L->next;          //q为要删除的结点
while (q != NULL)      //遍历头结点后的结点
{
    if (q->data == m)//找到指定结点,删除该结点后,q指针指向删除结点的后一结点,p不变
    {
        p->next = q->next;
        free(q);
        q = p->next;
    }
    else         //未找到该节点,p,q指针均向后移一个结点
    {
        p = q;
        q = q->next;
    }
}
return L;

}I
originally used a for loop to judge that step, but later found that the conditions are different in the two cases.
I hope it helps.

Guess you like

Origin blog.csdn.net/weixin_51235620/article/details/111385823