#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode* next;
};
struct ListNode* readlist() {
struct ListNode* phead = (struct ListNode*)calloc(1,sizeof(struct ListNode));
struct ListNode* ptail=phead;
while (phead)
{
struct ListNode* pnew = (struct ListNode*)calloc(1, sizeof(struct ListNode));
scanf_s("%d", &pnew->data);
if (pnew->data == -1)
break;
ptail->next = pnew;
ptail = pnew;
}
return phead;
}
struct ListNode* deletem(struct ListNode* L, int m) {
struct ListNode* ppre = L;
struct ListNode* pcur = ppre->next;
while (pcur) //当前节点不为空
{
if (pcur->data == m) { //当前结点要删除
ppre->next = pcur->next; //pcur前一个结点ppre的next指针指向后一结点
free(pcur);
pcur = ppre->next;
}
else { //当前节点不用删除
ppre = ppre->next;
pcur = pcur->next;
}
}
return L->next;
}
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_s("%d", &m);
L = deletem(L, m);
printlist(L);
return 0;
}
PAT习题11-8 单链表结点删除 (20 分)
最新推荐文章于 2023-01-07 13:41:24 发布