快慢指针练习

#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>

#define Maxsize 1000

typedef int Elemtype;
typedef int Status;

typedef struct node
{
	Elemtype data;
	struct node *next;
}Node;

typedef struct node *Linklist;

Status CreatListHead(Linklist *L,int n);
Status Getmidnode(Linklist L,Elemtype *e);
Status CreateListTail(Linklist *L,int n);
void PrintfList(Linklist L);
int ListLength(Linklist L);

int main(void)
{
	Linklist L,L1;
	Elemtype i,j;
	char ch;

    printf("1:头插法创建单链表\n2:尾插法创建单链表\n(输入0退出)\n");
    while(ch != '0')
    {
        scanf("%c",&ch);
        switch(ch)
        {
            case '1':
                CreatListHead(&L,6);
                PrintfList(L);
                ListLength(L);
                Getmidnode(L,&i);
            break;

            case '2':
                CreateListTail(&L1,9);
                PrintfList(L1);
                ListLength(L1);
                Getmidnode(L1,&j);
            break;

            case '0':
                exit(0);
            break;
        }
    }
	return 0;
}

Status CreatListHead(Linklist *L,int n)
{
	Linklist temp;
	int i;

	srand(time(0));

	*L = (Linklist)malloc(sizeof(Node));
	if(!(*L))
    {
        return 0;
    }

	(*L)->next = NULL;

	for(i = 0; i < n ;i++)
	{
		temp = (Linklist)malloc(sizeof(Node));
		temp->data = rand()%100 + 1;
		temp->next = (*L)->next;
		(*L)->next = temp;
	}

    return 1;
}

Status CreateListTail(Linklist *L,int n)
{
    Linklist temp,temp1;
    int i;

    *L = (Linklist)malloc(sizeof(Node));
    if(!(*L))
    {
        printf("尾插法内存分配失败\n");
        exit(1);
    }
    (*L)->next = NULL;
    temp1 = *L;

    for(i = 0;i < n;i++)
    {
        temp = (Linklist)malloc(sizeof(Node));
        temp->data = i;
        temp->next = temp1->next;
        temp1->next = temp;
        temp1 = temp;
    }
    temp1->next = NULL;

    return 0;
}


Status Getmidnode(Linklist L,Elemtype *e)
{
	Linklist search , mid;
	search = mid = L;

	while(search->next != NULL)
	{
        mid    = mid->next;
		if(search->next->next != NULL)
		{
			search = search->next->next;
        }
		else
		{
			search = search->next;
		}
	}
	*e = mid->data;
    printf("当前链表中间结点的值为:%d\n",*e);

	return 0;
}

void PrintfList(Linklist L)
{
    Linklist temp = L;

    while(!(temp->next == NULL))
    {
        temp = temp->next;
        printf("%d ",temp->data);
    }
    putchar('\n');
}

int ListLength(Linklist L)
{
    Linklist temp = L;
    int count = 0;

    while(temp->next != NULL)
    {
        temp = temp ->next;
        count++;
    }
    printf("该链表长度为:%d\n",count);
    return count;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值