zoukankan      html  css  js  c++  java
  • 有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点

    有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点

    解题思路:

    对于b链表中的每一个节点,都从a链表的表头开始查找,如果可以找到,直接删除,如果找不到,继续从a链表表头找下一个b的节点。

    #include <stdio.h>
    typedef struct student
    {
    	int num;
    	double grade;
    	struct student *next;
    } student;
    student *del(student *a, student *b)
    {
    	student *pre, *current, *head;
    	head = a;
    
    	while (b != NULL)
    	{
    		//重置指针指向a链表的头部
    		pre = head;
    		current = head->next;
    		//a 链表的头等于b
    		if (pre->num == b->num)
    		{
    			pre->next = NULL;
    			pre = current;
    			current = current->next;
    			//更新表头
    			head = pre;
    		}
    		else
    		{
    			while (pre->next != NULL)
    			{
    				if (current->num == b->num)
    				{
    					//找到就删除
    					pre->next = current->next;
    					break;
    				}
    				else
    				{
    					//否则继续遍历
    					pre = pre->next;
    					current = current->next;
    				}
    			}
    		}
    		b = b->next;
    	}
    	return head;
    }
    
    void printList(student *root)
    {
    	printf("----
    ");
    	int i = 0;
    	while (root != NULL)
    	{
    		printf("student %d -> %d -> %.2lf
    ", i, root->num, root->grade);
    		root = root->next;
    		i++;
    	}
    }
    
    int main()
    {
    	student a[3] = { { 1, 79 }, { 4, 36 }, { 5, 79 } };
    	for (int i = 0; i < 2; i++)
    	{
    		a[i].next = &a[i + 1];
    	}
    	a[2].next = NULL;
    	printf("链表a:
    ");
    	printList(&a[0]);
    
    	student b[2] = { { 5, 38 }, { 4, 98 } };
    	for (int i = 0; i < 1; i++)
    	{
    		b[i].next = &b[i + 1];
    	}
    	b[1].next = NULL;
    	printf("链表b:
    ");
    	printList(&b[0]);
    	student *combine = del(a, b);
    	printf("删除之后:
    ");
    	while (combine != NULL)
    	{
    		printf("%d -> %.2lf
    ", combine->num, combine->grade);
    		combine = combine->next;
    	}
    
    	return 0;
    }
    

    运行截图:
    有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点

  • 相关阅读:
    设计模式之第14章-命令模式(Java实现)
    设计模式之第13章-职责链模式(Java实现)
    设计模式之第12章-享元模式(Java实现)
    我的一年,过去,现在
    Reporting Services 的一些问题
    利用ICSharpCode进行压缩和解压缩
    利用System.Net.Mail 发送邮件
    利用Log4net组件记录日志
    系统权限的设计之简单设计
    利用NPOI组件产Excel完整操作
  • 原文地址:https://www.cnblogs.com/cyuyanchengxu/p/13470585.html
Copyright © 2011-2022 走看看