1-1 single chain table node deletion

1-1 single chain table node deletion

In this paper, two functions are required, one is to store the read-in data as a single linked list, and the other is to delete all nodes in the linked list that store a given value. The link list node is defined as follows:

truct ListNode {
int data;
ListNode *next;
};>

Function interface definition:

struct ListNode *readlist();
struct ListNode *deletem( struct ListNode *L, int m );

The readlist function reads a series of positive integers from the standard input, and creates a single chain table according to the reading order. When − 1 is read, it indicates the end of input, and the function should return a pointer to the single chain header node.
The delete function deletes all nodes in the single chain table L that store m. Returns a pointer to the result chain header node.

Sample referee test procedure:

#include <stdio.h>
#include <stdlib.h>
struct ListNode {
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;
}
/ Your code will be embedded here */>

Input example:

10 11 10 12 10 -1
10

Output example:

11 12

        struct ListNode *p,*tail,*head=NULL;
        while(1){
            scanf("%d",&a);
            if(a==-1) break;
            p=(struct ListNode *)malloc(sizeof(struct ListNode));
            p->data=a;
            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,*p1,*p2,*t;
        while(L!=NULL&&L->data==m){
            p=L;
            L=L->next;
            free(p);
        }
        if(L==NULL) return NULL;
        p1=L;
        p2=L->next;
        while(p2){
            if(p2->data==m) {
                p1->next=p2->next;
                free(p2);
            }
            else p1=p2;
            p2=p1->next;
        }
        return L;
    }

Added by blkraven on Thu, 21 Nov 2019 21:43:53 +0200