• 有两个链表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链表中有相同学号的那些结点

  • 相关阅读:
    N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法
    详细解释VB连接access几种方法数据库
    至少原则平方多项式曲线拟合和实施
    .net在arraylist用法
    Microsoft.AlphaImageLoader过滤评论
    总理推理算法(高效率
    mysql三学习sql声明学习
    1第一个Android应用程序
    软件架构学习总结
    ORACLE在表中添加的目光凝视和读取列
  • 原文地址:https://www.cnblogs.com/weiyidedaan/p/13331359.html
Copyright © 2020-2023  润新知