zoukankan      html  css  js  c++  java
  • 数据结构实验之链表五:单链表的拆分

    数据结构实验之链表五:单链表的拆分

    Time Limit: 1000MS Memory limit: 65536K

    题目描述

    输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。

    输入

    第一行输入整数N;;
    第二行依次输入N个整数。

    输出

    第一行分别输出偶数链表与奇数链表的元素个数; 
    第二行依次输出偶数子链表的所有数据;
    第三行依次输出奇数子链表的所有数据。

    示例输入

    10
    1 3 22 8 15 999 9 44 6 1001

    示例输出

    4 6
    22 8 44 6 
    1 3 15 999 9 1001

    代码感觉很乱。我会尽快把本事学到家。优化下。

    #include <stdio.h>
    #include <stdlib.h>
    
    struct LNode
    {
    	int data;
    	struct LNode *next;
    };
    
    void creat(struct LNode *head,int n);
    int getsize(struct LNode *head);
    void print(struct LNode *head);
    
    int main()
    {
    //	freopen("my.in","r",stdin);
    		
    	struct LNode h1,h2,h3;//h2偶数,h3奇数
    	struct LNode *tail1,*tail2,*tail3;
    	struct LNode *p;
    	int n;
    	scanf("%d",&n);
    	creat(&h1,n);
    	tail1 = h1.next;
    	tail2 = &h2;
    	tail3 = &h3;
    	while(tail1)//知道h1处理完
    	{
    		if(tail1->data % 2 == 0)//如果为偶数
    		{
    			p = (struct LNode *)malloc(sizeof(struct LNode));
    			p->next = NULL;
    			p->data = tail1->data;
    			tail2->next = p;
    			tail2 = p;	
    		}	//
    		else//如果为奇数
    		{
    			p = (struct LNode *)malloc(sizeof(struct LNode));
    			p->next = NULL;
    			p->data = tail1->data;
    			tail3->next = p;
    			tail3 = p;	
    		}		
    		tail1 = tail1->next;	
    	}
    	printf("%d %d\n",getsize(&h2),getsize(&h3));
    	print(&h2);
    	print(&h3);
    	return 0;		
    }
    void creat(struct LNode *head,int n)
    {
    	struct LNode *tail,*p;
    	int i;
    	tail = head;
    	tail->next = NULL;
    	for(i=0; i<n; i++)
    	{
    		p = (struct LNode *)malloc(sizeof(struct LNode));
    		p->next = NULL;
    		scanf("%d", &p->data);
    		tail->next = p;
    		tail = p;
    	}
    }
    
    void print(struct LNode *head)
    {
    	struct LNode *p;
    	p = head->next;
    	while(p->next)
    	{
    		printf("%d ",p->data);
    		p = p->next;
    	}
    	printf("%d\n",p->data);
    }
    
    int getsize(struct LNode *head)
    {
    	struct LNode *p;
    	int n=0;
    	p = head->next;
    	while(p)
    	{
    		n++;
    		p = p->next;
    	}
    	return n;
    }
    



  • 相关阅读:
    Java学习笔记
    Winform中ListView设置了ColumnHeader不显示问题
    GitHub私有仓库为他人授权
    (转)一步一步教你如何在GitHub上上传自己的项目
    【转】C#中的Explicit和Implicit
    C#对象深表复制方法
    mongodb 设置 ssl
    zabbix 4.0.1部署
    redis编译安装
    VMware网络连接模式——桥接模式、NAT模式以及仅主机模式的介绍和区别
  • 原文地址:https://www.cnblogs.com/tanhehe/p/2883526.html
Copyright © 2011-2022 走看看