删除一个单项链表的最中间的元素,要求时间尽可能短(不能使用两次循环)

#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\t",plink->data);      
                plink = plink->next;
            }
            printf("\n");   
    }
}
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    

 

posted @ 2013-10-30 21:42  夜雨阑珊  阅读(324)  评论(0编辑  收藏  举报