• 未知链表的求中间位置


    直接上代码:

    /*
    
    设置两个指针*one、*two都指向单链表的头节点。其中* two的移动速度是*one的2倍。当* two指向末尾节点的时候,*one正好就在中间了。
    
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    #define LEN sizeof(struct node)
    
    struct node
    {
    	int date;
    	struct node *next;
    };
    
    struct node *CreateList();
    void TraverseList(struct node * head);
    struct node *findmid(struct node *head);
    struct node *findmid(struct node *head);
    
    //
    struct node *CreateList()
    {
    	struct node * head;//头结点
    	struct node * pcurrent;//保存新创建结点的地址
    	struct node * tail;//保存原链表最后一个接结点的地址
    	int num=0;
    	//int n=0;
    
    	head=tail=NULL; /*开始 head and tail指向 NULL*/ 
    
    	scanf("%d",&num);
    	while(num!=0)/*只要学号不为 0,就继续录入下一个节点*/
    	{
    		pcurrent=(struct node *)malloc(LEN);
    		pcurrent->date=num;
    		pcurrent->next=NULL;
    		if(head==NULL)
    			head=pcurrent;
    		else
    			tail->next=pcurrent;
    		//尾指针指向新的表尾
    		tail=pcurrent;
    		scanf("%d",&num);
    	}
    	//返回头指针 
    	return head;
    }
    
    void TraverseList(struct node * head)
    {
    	struct node * ptr;
    	if(head==NULL)
    	{
    		printf("No Records");
    		exit(0);
    	}
    	else
    	{
    		for(ptr=head; ptr; ptr=ptr->next)
    			printf("%d\n",ptr->date);
    	}
    }
    
    struct node *findmid(struct node *head)
    {
    	struct node *one = head, *two = head;
    	while(two != NULL)
    	{
    		two = two->next;
    		if(two != NULL)
    		{
    			two = two->next;
    			one = one->next;
    		}
    	}
    	return one;
    }
    
    int main(void)
    {
    	struct node * head;//head 用来放链表头结点的地址
    	struct node * mid;
    	//struct node * ptr;
    	
    	puts("......Find middle element......\n");
    	puts("Input numbers in the next line:\n");
    	
    	head=(struct node *)malloc(LEN);
    	
    	head=CreateList();
    	printf("The list members are :============================\n");
    	//遍历链表
    	TraverseList(head);//遍历 
    	
    	mid = findmid(head);
    	printf("mid = %d\n",mid->date);
    	
    	return 0;
    }
    
    



  • 相关阅读:
    算法导论(1)堆排序
    Opencv--HoughCircles源码剖析
    数据结构算法应用C++语言描述——(1)C++基础知识
    Java编程的23种设计模式
    团队建设
    管理方法论和角色认知
    压力测试:怎样设计全链路压力测试平台
    09-数据库优化方案(二):写入数据量增加时,如何实现分库分表
    08-数据库优化方案(一):查询请求增加时,如何做主从分离
    07-池化技术:如何减少频繁创建数据库连接的性能损耗
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/12007666.html
Copyright © 2020-2023  润新知