Output the last K elements of a set of data input from the keyboard

Output the last K elements of a set of data input from the keyboard

topic

Please write an algorithm to sequentially output the last K elements of a set of data entered through the keyboard.
Convention: End with CTRL+Z as the keyboard input, and assume that K<=the number of data elements entered.
Requirements: No arrays can appear in the algorithm, and no process of calculating the number of input data is allowed.

analysis

A single circular linked list with no leading nodes is used to establish a single circular linked list with K nodes. Every time a number is entered, it is stored in the linked list. At the end of the input, the elements in the linked list are the last K elements.

Code

typedef struct node{   
	int data;   
	struct node *link;
}BNode,*LinkList;

void PRINTENDK(int k){    
	LinkList list=NULL,p,r;    
	int a;    
	for (int i = 1; i <= k; i++)    {        
		p=(LinkList)malloc(sizeof(BNode));        
		p->data=0;        
		if (list ==NULL)        {            
			list=p;       
		}else{           
			 r->link=p;       
		 }       
		 r=p;    
	}    
	p->link=list;     //建立循环链表,让p的link指向list
	p=list;  // p指向初始的位置
	while (scanf("%d",&a)>0)    {       
		p->data=a;       
		p=p->link;    
	}    
	for (int i = 1; i <=k; i++)    {        
		if (p->data!=0)        {           
			printf("%d,",p->data);        
		}        
		p=p->link;      
	}    
}

Guess you like

Origin blog.csdn.net/honeylife/article/details/98963472