从一个链表channelHead中删除和channelToDeleteHead中相同的元素

来源:互联网 发布:医疗数据公司 编辑:程序博客网 时间:2024/06/07 05:55
#include <iostream>using namespace std;//从一个链表head1中删除和head2中相同的元素struct Node{Node(int x){value = x;next = NULL;}int value;Node *next;};//共同点用一个节点Node *pre来标志是否要更新头节点//方法一:unsigned int deleteDuplication1(Node **head1, Node *head2){int count = 0;while (head2){Node *pre = NULL;Node *cur = *head1;//原链表的节点while (cur){if (cur->value == head2->value){count++;Node *pNext = cur->next;//先保留cur的下一个节点delete cur;cur = pNext;if (pre == NULL)//说明在链表head1中,此时的cur前面还没出现与head2这个节点不同的元素*head1 = cur;elsepre->next = cur;}else{pre = cur;cur = cur->next;}}head2 = head2->next;}return count;}//方法二unsigned int deleteDuplication2(Node **head1, Node *head2){int count = 0;while (head2){Node *pre = NULL;Node *cur = *head1;while (cur){bool needDelete = false;if (cur->value == head2->value)needDelete = true;if (!needDelete){pre = cur;cur = cur->next;}else{int value = cur->value;Node *pNext = NULL;while (cur && cur->value == value)//与方法一的不同之处多了一个循环{count++;pNext = cur->next;//保留cur的下一个节点delete cur;cur = pNext;}if (pre == NULL)//说明在链表head1中,此时的cur前面还没出现与head2这个节点不同的元素*head1 = cur;elsepre->next = cur;}}head2 = head2->next;}return count;}void print(Node *head){while (head){cout << head->value << " ";head = head->next;}cout << endl;}int main(){//建立第1个链表Node *p1 = new Node(3);Node *p2 = new Node(2);Node *p3 = new Node(3);Node *p4 = new Node(3);Node *p5 = new Node(4);Node *p6 = new Node(4);p1->next = p2;p2->next = p3;p3->next = p4;p4->next = p5;p5->next = p6;//打印第1个链表print(p1);//建立第2个链表Node *q1 = new Node(3);Node *q2 = new Node(3);Node *q3 = new Node(4);Node *q4 = new Node(4);q1->next = q2;q2->next = q3;q3->next = q4;//打印第2个链表print(q1);int count = deleteDuplication1(&p1, q1);//int count = deleteDuplication2(&p1, q1);//删除之后,打印printf("删除后,第一个链表为:\n");print(p1);cout << "删除的个数为:" << count << endl;return 0;}


                                             
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 刚出生的宝宝不吃母乳怎么办 宝宝六个月奶不够吃怎么办 六个月奶不够吃怎么办 刚出生奶不够吃怎么办 做梦醒了看见鬼怎么办 宝宝到陌生地方哭闹怎么办 大人生病住院小孩没人带怎么办 孕妇被小猫抓了怎么办 怀孕了家里有猫怎么办 厕所被湿纸巾堵了怎么办 5天新生儿不拉屎怎么办 4月宝宝不拉屎怎么办 两岁宝宝晚上睡觉哭闹怎么办 2月婴儿吐奶很多怎么办 心情不好回奶了怎么办 四个月了没奶怎么办 八岁宝宝还尿床怎么办 自己一人在家害怕怎么办 被猫抓伤流血了怎么办 被小狐狸咬了怎么办 怀孕吃了兔子肉怎么办 鸟总在窗子上啄怎么办? 有鸟飞进楼道里怎么办 租的房间房东要求改建怎么办 小偷偷钱抓住不还钱怎么办 损友圈羊被陌生人偷了怎么办 在酒店如果遇到客人偷东西怎么办 梦见家里有不好的东西怎么办 被小孩要破了怎么办啊 租一个房子小孩一进房就哭怎么办 墙缝里有蝙蝠窝怎么办 小蝙蝠在墙缝里怎么办 小孩一进屋就哭怎么办 屋门对着厕所门怎么办 入室门对厨房门怎么办 厕所正对入户门怎么办 小区楼交错冲路怎么办 床的位置在五鬼上怎么办 被甩了很痛苦怎么办 和对象想分手了怎么办 对象想跟你啪啪怎么办