C语言问题:删除数组中的元素(链表)

2025-03-06 02:31:24
推荐回答(1个)
回答1:

#include

struct node

{

int data;

node *next;

};

void creat(node *head,int);

void remove(node *head,int);

void print(node *head);

void main()

{

int count; //数字总数

int num;//要删除的数字

node *head=new node;

do

{

cout<<"依次输入个数n(1<=n<=200000),n个元素(用空格分隔),待删除的元素。"<

cin>>count;

}

while(count>200000||count<1);

creat(head,count);

cin>>num;

remove(head,num);

cout<<"结果如下:"<

print(head);

}

void creat(node *head,int i)

{

node *temp;

head->next=NULL;

while(i--)

{

temp=new node;

cin>>temp->data;

temp->next=head->next;

head->next=temp;

head=temp;

}

}


void remove(node *head,int num)

{

node *p=head;

head=head->next;


while(head!=NULL)

{

if(head->data==num)

{

p->next=head->next;

head=p->next;


}

else

{

p=p->next;

head=head->next;

}

}


}


void print(node *head)

{

head=head->next;

while(head!=NULL)

{

cout<data<<' ';

head=head->next;

}

cout<

}

运行结果如下: