C++单链条中删除节点相同的数据

#include <stdio.h>

#include <malloc.h>

typedef struct Node

{

int data;

struct Node *next;

}Node;

//创建类型和用尾插法创建单链条博主在创建单链条中已经解释过 不了解的可以去看一下

Node *list()

{

Node *head=NULL,*tail=NULL;

int count;

printf("input all number's number:");

scanf("%d",&count);

for(int i=1;i<=count;i++)

{

printf("input No%d number:",i);

Node *num=(Node *)malloc(sizeof(Node));

scanf("%d",&num->data);

num->next=NULL;

if(head==NULL)

{

head=tail=num;

}

else

{

tail->next=num;

tail=num;

}

}

return head;

}

Node *delect_two(Node *head)

{

int pop_num;

printf("please input u want to delect number:\n");

scanf("%d",&pop_num);

Node *No1_head = NULL,*No2_head = NULL; //两个连续的指针方便遍历和运用

No1_head = No2_head = head;//都赋予头指针的功能

while(No2_head != NULL)//要寻找多个删除的位置

{

if(No2_head->data == pop_num)//满足这个条件 会出现 1就是头指针的值 2不是头指针的值情况

{

if(No2_head == head)//情况1的解决方法

{

head = head->next;//头指针向后移动一个节点

free(No2_head);//回收No2_head节点

No1_head = No2_head = head;//重新赋予No2_head功能满足遍历需要

}

else

{

No1_head->next = No2_head->next;//用指针的功能跳过与要删除的值相等的No2_head节点

free(No2_head);//回收No2_head节点

No2_head = No1_head->next; //重新赋予No2_head功能满足遍历需要

}

}

else

{

No1_head = No2_head;

No2_head = No2_head->next;//遍历

}

}

return head;

}

void read(Node *head)

{

while(head!=NULL)

{

printf("%3d",head->data);//遍历整个链条

head=head->next;

}

}

int main()

{

Node *head = list();

Node *new_head = delect_two(head);//调用相应函数

read(new_head);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值