求助求助!!!用c语言实现
本帖最后由 看清之后才看轻 于 2021-4-14 15:15 编辑输入若干的正整数(输入-1时结束) ,建立一个单向链表;再输入一正整数m,删除链表中值为m的所有节点。(用c实现)
本帖最后由 henkuderen 于 2021-4-14 17:26 编辑
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int data;
struct ListNode *next;
};
struct ListNode *readlist();
struct ListNode *delete_val( 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 val;
printf("连续输入多个整数(-1表示结束):");
struct ListNode *L = readlist();
printf("\n链表的数据: ");
printlist(L);
printf("输入要删除的整数:");
scanf("%d", &val);
L = delete_val(L, val);
printlist(L);
return 0;
}
struct ListNode *readlist()
{
struct ListNode *head,*p1,*p2;
int num;
int size = sizeof(struct ListNode);
head = NULL;
while(1)
{
scanf("%d", &num);
if(num == -1) //-1跳出
{
break;
}
p1 = (struct ListNode*)malloc(size);
p1->data = num;
p1->next = NULL;
if(head == NULL)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
}
return head;
}
struct ListNode *delete_val( struct ListNode *L, int val )
{
struct ListNode *ptr, *ptr1;
while( L != NULL && ( L->data == val) )
{
ptr1 = L;
L = L->next;
free(ptr1);
}
if( L == NULL )
return NULL;
ptr = L;
ptr1 = L->next;
while( ptr1 != NULL)
{
if( ptr1->data == val )
{
ptr->next = ptr1->next;
free(ptr1);
}
else
ptr = ptr1;
ptr1 = ptr->next;
}
return L;
}
页:
[1]