单链表例题

题目:快速找到未知长度单链表的中间节点

普通方法: 遍历一遍单链表以确定单链表的长度L,然后再次从头节点出发循环L/2次即可找到单链表的中间节点。算法复杂度为O(L+L/2)=O(3L/2).
高级方法: 利用快慢指针原理:设置两个指针search、mid都指向单链表的头节点。其中search的移动速度是mid的2倍。这样当*search指向末尾节点的时候,*mid正好就在中间。这也是标尺的思想。算法复杂度为O(L/2)。

Status GetMidNode(LinkList L, ElemType *e)
{
     
    LinkList search,mid;
    mid=search=L;

    while(search->next!=NULL)
    {
     
        if(search->next->next != null)
        {
     
            search=search->next->next;
            mid=mid->next;
        }
        else
        {
     
            search=search->next;
        }

    }
    *e=mid->data;
    
    return OK;
}

题目:写一个完整的程序,实现随机生成若干个元素的链表(尾插法或头插法随意),快速查找中间结点的值并显示

#include
#include
#include
#include
#include
struct node
	{
     
		 int data;     //elementype表示一种数据类型,可能是int/char等等
		 struct node *next;   //next 指针,用于链表结构指向下一个节点
	};
	typedef struct node node; //重定义struct node类型为node

	int GetMidNode(node* L);
	void List(node* head);
	node* Creat(int Count);
	int Length(node *L);


	int main()
	{
     
	node* head;
//	head = Creat(20);
//	List(head);
//	printf("%d",Length(head));
//		printf("%d",GetMidNode(head));
	int a;
	int Num;
	printf("1.查看链表\n2.创建链表\n3.链表长度\n4.中间节点值\n0.退出\n");
	while(1)
	{
     

	scanf("%d",&a);
	switch(a)
	{
     

		case 1:
			printf("List:\n");
			List(head);
			printf("\n");
			break;
		case 2:
			printf("输入创建链表节点数:\n");
			scanf("%d",&Num);
			head = Creat(Num);
			printf("\n");
			break;
		case 3:
			printf("链表长度:\n");
			printf("%d",Length(head));
			printf("\n");
			break;
		case 4:
			printf("中间节点值:\n");
			printf("%d",GetMidNode(head));
			printf("\n");
			break;
		case 0:
			return 0;
	}

	}
	return 0;
	}
	int n;
	node* Creat(int Count)
	{
     
		node *p1,*p2,*head;
		n = 0;
		srand(time(NULL));//生成种子
		p1 = p2 = (node*)malloc(sizeof(node));
	//	scanf("%d",&p1->data);
		p1->data = rand()%1000;
		head = NULL;
		while(n < Count)
		{
     
			n = n+1;
			if(n == 1)
			{
     
				head = p1;

			}
			else
			{
     
				p2->next = p1;

			}
			p2 = p1;
			p1 = (node*)malloc(sizeof(node));
	//		scanf("%d",&p1->data);
			p1->data = rand()%1000;

		}
		p2->next = NULL;
		return(head);
	}
	void List(node* head)
	{
     
		node *p1;
		p1 = head;
		while(p1!= NULL)
		{
     

			printf("%d\n",p1->data);
			p1 = p1->next;
		}
	}
	int GetMidNode(node* L)
	{
     
		int a;
		node *search,*mid;
		mid = search = L;
		while(search->next != NULL)
		{
     
			if(search->next->next != NULL)
			{
     
				search = search->next->next;
				mid= mid->next;
			}
			else
			{
     
				search = search->next;
			}
		}
		a = mid->data;
		return a;
	}
	int Length(node *L)
	{
     
	    int n=0;
	    while(L->next!=NULL)
        {
     
            n++;
            L=L->next;
        }
        n++;
        return n;
	}

你可能感兴趣的:(单链表例题)