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    
  • 相关阅读:
    web.xml配置文件
    数组去重问题
    Mysql优化
    点赞功能
    IDEA的一些使用小技巧
    Maven
    AJAX
    HTTP响应头拆分/CRLF注入详解
    对寄存器ESP和EBP的一些理解
    汇编调用指令的执行过程
  • 原文地址:https://www.cnblogs.com/fickleness/p/3397835.html
Copyright © 2011-2022 走看看