1. 程式人生 > >單鏈表實現查詢中間結點

單鏈表實現查詢中間結點

題目:

使用者輸入x;

隨機生成X個元素,輸出中間元素。

若為奇數則輸出中間,若為偶數輸出中間兩個數的平均值

連結串列實現

具體實現演算法

(1)定義兩個指標,首先將他們指向第一個元素

(2)快慢指標,快指標p1是慢指標p2的2倍速度。相當於p1+2,p2++;

(3)考慮可能是偶數個元素,快指標p1->next為空時,直接輸出慢速度p2所指的元素,並跳出迴圈。

               若為奇數,直接輸出慢速度p2所指的元素。

原始碼如下:

/*
使用者輸入x;
隨機生成X個元素,輸出中間元素。
若為奇數則輸出中間,若為偶數輸出中間兩個數的平均值
連結串列實現
*單鏈表的中間結點
*快慢指標都是頭指標快指標是慢指標的2倍速度。
*/
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define random(x) (rand()%x)//隨機數0-100

typedef int Elemtype;
typedef struct Node{
	Elemtype data;
	struct Node *next;
};
typedef struct Node * LinkList;

void ListShow(LinkList L);
void ListInsert(LinkList L, int num);
void SearchMid(LinkList L);
int ListLength(LinkList L);

void main()
{
	LinkList L;
	L = ( LinkList )malloc( sizeof (Node));//L->next為第一個元素,L為指向頭結點的指標
    L->next = NULL;  
	int x,length;
	printf("\n");
	printf("請輸入隨機數連結串列的長度:\n");
	scanf("%d",&x);
	printf("\n");
	while(x--)
	{
	   ListInsert(L,random(100));
	}
	 length=ListLength(L); 
	 printf("當前連結串列長度為:%2d\n",length);
	 ListShow(L);
	 SearchMid(L);
}	
void ListInsert(LinkList L, int num)  //尾插法建立連結串列  
{   	
	LinkList temp = L;  //temp為尾指標
    LinkList new_node = NULL;  
    new_node = (LinkList)malloc(sizeof(Node));  
    if (!new_node)  
    {  
        printf("memory out of use/n");  
    }   
	while (temp->next != NULL)     //尋找尾結點
    {  
        temp = temp->next;  
    }  
    new_node->data = num;  
    new_node->next = NULL;  
	temp->next= new_node;  
	temp=new_node;   
}  
void ListShow(LinkList L)  
{  
    LinkList temp; 
	temp=L->next;
	printf("*******************當前連結串列元素為:************\n");
    while(temp)  
    {  
       printf("%3d\t" ,temp->data);
       temp = temp->next;  
    } 
	printf("\n");
  
}  
void SearchMid(LinkList L){
	  LinkList p1,p2,t; //p1為快指標+2,p2為慢指標+1
	  p1=p2=t=L->next;
      float Mid;
	while (p1->next != NULL)     //尋找尾結點
    {  
		t=p1->next;  
		if(t->next==NULL)
		{
			Mid=0.5*(p2->data+p2->next->data);
			printf("\n------------偶數個元素中間值為%.2f-----------------\n\n",Mid);	
			exit(0);
		}	
		else
		{
		  p1=t->next;
		  p2=p2->next;
		}		
    } 
	printf("\n------------奇數個元素中間值為%d-------------------\n\n",p2->data);
	
}
int ListLength(LinkList L)
{
	LinkList t; 
	t=L->next;
    int length=0;
	while (t->next != NULL)     //尋找尾結點
    {  
		t=t->next;  
		length++;
	}
	return length+1;
}

截圖:

例如

(1)連結串列總長度為奇數9



(2)連結串列總長度為偶數20