本題要求實現兩個函數,分別將讀入的數據儲存爲單鏈表、將鏈表中所有儲存了某給定值的結點刪除。鏈表結點定義如下:
struct ListNode {
int data;
ListNode *next;
};
函數介面定義:
struct ListNode *readlist();
struct ListNode *deletem( struct ListNode *L, int m );
函數readlist
從標準輸入讀入一系列正整數,按照讀入順序建立單鏈表。當讀到−1時表示輸入結束,函數應返回指向單鏈表頭結點的指針。
函數deletem
將單鏈表L
中所有儲存了m
的結點刪除。返回指向結果鏈表頭結點的指針。
裁判測試程式樣例:
#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;
}
/* 你的程式碼將被嵌在這裏 */
輸入樣例:
10 11 10 12 10 -1
10
輸出樣例:
11 12
----------------------------------------------------------------------------------------------------------------------------------------------------------
struct ListNode* readlist() {
struct ListNode* prev, * current;
struct ListNode* head = NULL;
int num;
do {
scanf("%d", &num);
if (num != -1) {
current = (struct ListNode*)malloc(sizeof(struct ListNode));
if (head == NULL)head = current;
else prev->next = current;
current->next = NULL;
current->data = num;
prev = current;
}
} while (num != -1);
return head;
}
struct ListNode* deletem(struct ListNode* L, int m) {
struct ListNode* p = L;
struct ListNode* q = p;
while (p) {
if (p->data == m) {
if (p == L) {
L = p->next;
}
else {
q->next = p->next;
}
p = p->next;
}
else {
q = p;
p = p->next;
}
}
return L;
}