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:
struct 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 (p) { 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
Code:
struct ListNode *readlist() { struct ListNode *p=NULL,*head=NULL,*tail=NULL; int data; head=(struct ListNode*)malloc(sizeof(struct ListNode)); head->next=NULL; tail=head; scanf("%d",&data); while(1) { if(data==-1)break; p=(struct ListNode*)malloc(sizeof(struct ListNode)); p->data=data; p->next=NULL; //????????????????????????????????????? //tail=p; ?? tail->next=p; //Note: these two sentences?? tail=p; //Can't exchange order?? //????????????????????????????????????? scanf("%d",&data); } return head; } struct ListNode *deletem( struct ListNode *L, int m ) { struct ListNode *p=L; int flag; while(p->next!=NULL) { flag=0; if(p->next->data<=m) { p->next=p->next->next; flag=1; } if(flag==0)p=p->next; } return L->next; }