習題11-8 單鏈表結點刪除 (20 分)
1. 題目摘自
https://pintia.cn/problem-sets/12/problems/366
2. 題目內容
本題要求實現(xiàn)兩個函數,分別將讀入的數據存儲為單鏈表牙言、將鏈表中所有存儲了某給定值的結點刪除酸钦。鏈表結點定義如下:
struct ListNode {
int data;
ListNode *next;
};
函數接口定義:
struct ListNode *readlist();
struct ListNode *deletem( struct ListNode *L, int m );
函數readlist從標準輸入讀入一系列正整數,按照讀入順序建立單鏈表嬉挡。當讀到?1時表示輸入結束钝鸽,函數應返回指向單鏈表頭結點的指針。
函數deletem將單鏈表L中所有存儲了m的結點刪除庞钢。返回指向結果鏈表頭結點的指針拔恰。
輸入樣例:
10 11 10 12 10 -1
10
輸出樣例:
11 12
3. 源碼參考
#include <iostream>
#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;
}
struct ListNode *readlist()
{
int n;
struct ListNode *h, *t, *p;
h = t = NULL;
scanf("%d", &n);
while (n != -1)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->data = n;
p->next = NULL;
if (h == NULL)
{
h = p;
}
else
{
t->next = p;
}
t = p;
scanf("%d", &n);
}
return h;
}
struct ListNode *deletem(struct ListNode *L, int m)
{
struct ListNode *p, *q;
while ((L != NULL) && (L->data == m))
{
q = L;
L = L->next;
free(q);
}
if (L == NULL)
{
return L;
}
p = L;
q = L->next;
while (q != NULL)
{
if (q->data == m)
{
p->next = q->next;
free(q);
}
else
{
p = q;
}
q = p->next;
}
return L;
}