/两个(list)集合{"a","b","b","d","e"}和{"d","e","f","g","h"},把这两个集合取出重复项合并成一个。

/两个(list)集合{"a","b","b","d","e"}和{"d","e","f","g","h"},把这两个集合取出重复项合并成一个。

static void Main(string[] args)
        {
            //两个(list)集合{"a","b","b","d","e"}和{"d","e","f","g","h"},把这两个集合取出重复项合并成一个。 

            List<string> listOne = new List<string>() { "a", "b", "b", "d", "e" };
            List<string> listTwo = new List<string>() { "d", "e", "f", "g", "h" };

            for(int i= 0; i < listTwo.Count; i++)
            {
                if (!listOne.Contains(listTwo[i]))
                {
                    listOne.Add(listTwo[i]);//不包含该元素,就把该元素扔进来

                }
            }

            for(int i = 0; i < listOne.Count; i++)
            {
                Console.WriteLine(listOne[i]);
            }

            Console.ReadKey();
            //Console.WriteLine("可以不");r5
            //Console.ReadKey();


        }

 

为了在C++中使用单链表实现集合的交运算,我们可以创建两个链表,分别存储集合A和集合B的元素,并遍历它们找出共同的部分。这里是一个简单的实现示例: ```cpp #include <iostream> #include <string> // 单链表节点结构体 struct ListNode { std::string value; ListNode* next; }; // 创建链表节点 ListNode* createNode(std::string val) { ListNode* node = new ListNode(); node->value = val; node->next = nullptr; return node; } // 添加元素到链表 void addToList(ListNode*& head, std::string val) { ListNode* newNode = createNode(val); if (head == nullptr) { head = newNode; } else { ListNode* curr = head; while (curr->next != nullptr) { curr = curr->next; } curr->next = newNode; } } // 遍历链表并打印元素 void printList(ListNode* head) { ListNode* temp = head; while (temp != nullptr) { std::cout << temp->value << " "; temp = temp->next; } std::cout << std::endl; } // 计算交集并将结果添加到新的链表 ListNode* computeIntersection(ListNode* listA, ListNode* listB) { ListNode* resultHead = nullptr; ListNode* AIt = listA; ListNode* BIt = listB; while (AIt != nullptr && BIt != nullptr) { if (AIt->value == BIt->value) { addToList(resultHead, AIt->value); // 如果值相同,将其添加到结果链表 } if (AIt->value > BIt->value) { BIt = BIt->next; } else { AIt = AIt->next; } } return resultHead; } int main() { // 初始化集合A和B ListNode* listA = nullptr; addToList(listA, "c"); addToList(listA, "a"); addToList(listA, "e"); addToList(listA, "h"); ListNode* listB = nullptr; addToList(listB, "f"); addToList(listB, "h"); addToList(listB, "b"); addToList(listB, "g"); addToList(listB, "d"); addToList(listB, "a"); // 计算交集 ListNode* intersectionList = computeIntersection(listA, listB); // 打印结果 std::cout << "交集: "; printList(intersectionList); return 0; } ``` 这个程序首先创建了两个链表`listA`和`listB`,然后通过`computeIntersection`函数计算它们的交集。最后,`printList`函数将结果打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值