zoukankan      html  css  js  c++  java
  • 删除一个单项链表的最中间的元素,要求时间尽可能短(不能使用两次循环)

    #include<stdio.h>
    #include<stdlib.h>
    #include<stddef.h>
    #include<malloc.h>
    struct link
    {
        int data;
        struct link *next;
    };
    void delMiddle(link *head)
    {
        if(head == NULL)
               return;
        else if(head->next == NULL)
        {
                delete head;
                return;
        }
        else
        {
                link *low = head;
                link *fast = head->next;
                while(fast != NULL && fast->next != NULL)
                {   
                           fast = fast->next->next;
                           if(fast == NULL)
                                        break;
                           low = low->next;
                }
                link *temp = low->next;
                low->next = low->next->next;
                delete temp;
    
        }
    }
    void print(link *head)
    {
    if(head == NULL)
               return;
        else if(head->next == NULL)
        {
                delete head;
                return;
        }
        else
        {
                link *plink = head;
                while(plink != NULL )
                {   
                    printf("%d	",plink->data);      
                    plink = plink->next;
                }
                printf("
    ");   
        }
    }
    int main()
    {
           struct link *head,*l;
           struct link *s;
           head = (link*)malloc(sizeof(link));
           head->data=0;
           head->next = NULL;
           l = head;
           int n;
           
           scanf("%d",&n);       
           for(int i=1; i<n; i++)
           {
                s = (link*)malloc(sizeof(link));
                s->data = i;
                s->next = NULL;
                l->next= s;
                l = l->next;
           }
           print(head);
           delMiddle(head);
           print(head);
           return 0;
    }
    Test Case
    n=0,1,2
    n>2 奇数 n=9
    0 1 2 3 4 5 6 7 8
    0 1 2 3 5 6 7 8
    n>2 偶数 n=10
    0 1 2 3 4 5 6 7 8 9
    0 1 2 3 4 6 7 8   9    
  • 相关阅读:
    maven更新远程仓库速度太慢解决方法
    maven安装配置
    myeclipse中配置maven
    java数组的常用函数
    在数组中插入元素
    MySQL的表使用
    MySQL的数据库与表格创建
    节点的添加与删除
    html常用的综合体
    标签的类添加与删除
  • 原文地址:https://www.cnblogs.com/fickleness/p/3397835.html
Copyright © 2011-2022 走看看