给定一个单向链表(长度未知),请遍历一次就找到中间的指针,假设该链表存储在只读存储器,不能被修改

给定一个单向链表(长度未知),请遍历一次就找到中间的指针,假设该链表存储在只读存储器,不能被修改

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

struct listElementType
{
    int data;
    listElementType* next;
};

typedef struct listElementType* m_list;


m_list createList(const int& u_listLength)
{
    m_list head = NULL,p1 = NULL,tail = NULL;
    int i = 0,a = 0;
    for (i = 1; i <= u_listLength; i++)
    {
        p1 = (m_list)malloc(sizeof(m_list));
        if (p1 != NULL)
        {
            printf("input the %d th number of list:",i);
            scanf("%d",&a);
            p1->data = a;
            if (head == NULL)
            {
                head = p1;
                tail = p1;
            }
            else
            {
                tail->next = p1;
                tail = p1;
            }
            tail->next = NULL;
        }
        else
        {
            printf("i:%d malloc p1 failure\n",i);
        }
    }
    return head;
}

void printList(m_list u_list)
{
    while (u_list)
    {
        printf("%d ",u_list->data);
        u_list = u_list->next;
    }
}

void freeList(m_list u_list)
{
    m_list p1 = NULL;
    while (u_list != NULL)
    {
        p1 = u_list;
        u_list = u_list->next;
        free(p1);
        p1 = NULL;
    }
}

void find_middle_element_from_list(m_list u_list,m_list& u_listRetNode1,m_list& u_listRetNode2)
{
    if (u_list == NULL)
    {
        printf("error:the source list is NULL\n");
        return ;
    }

    m_list p1 = NULL,p2 = NULL;
    int u_p1_off_set = 0;
    p1 = u_list;
    p2 = u_list;
    
    while (p1->next)
    {
        p1 = p1->next;
        u_p1_off_set += 1;
        if (p1->next)
        {
            p1 = p1->next;
            u_p1_off_set += 1;
            p2 = p2->next;
        }
    }
    if (u_p1_off_set%2 == 0)
    {
        u_listRetNode1 = p2;
    }
    else
    {
        u_listRetNode1 = p2;
        u_listRetNode2 = p2->next;
    }
}

int main(void)
{
    int u_listLength = 0;
    printf("input the list length:");
    scanf("%d",&u_listLength);
    
    m_list u_list = createList(u_listLength);
    if (u_list)
    {
        printList(u_list);
        m_list u_dstListNode1 = NULL,u_dstListNode2 = NULL;
        find_middle_element_from_list(u_list,u_dstListNode1,u_dstListNode2);
        if (u_dstListNode1)
        {
            printf("dstListNode1:%d\n",u_dstListNode1->data);
        }
        if (u_dstListNode2)
        {
            printf("dstListNode2:%d\n",u_dstListNode2->data);
        }
    }
    else
    {
        printf("create list failure,listLength:%d\n",u_listLength);
        return -1;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值