删除列表中的元素

时间:2016-01-25 06:01:56

标签: data-structures linked-list

删除链接列表: 题: Aaliyaa小姐有很多男朋友,对她来说都不是TrustWorthy。所以她决定按照我们的两条规则删除所有联系人。 如果没有男朋友,那么她会从她的手机中删除第n / 2个联系人。 2.如果没有男朋友在计算,那么她将第n / 2个联系人和第(n / 2 + 1)个联系人加起来。 最后删除第n / 2个联系人。在一天结束时,她与她没有联系。 帮助Aaliyaa找出删除其联系人的顺序。 样本输入

5

1 2 3 4 5

示例输出

3 6 4 6 5

解释

Following rule 1 the middle element 3 is deleted.
The list becomes 1 2 4 5
Following rule 2 The list becomes 1 6 4 5, (6=2+4)
After deleting 6 the list becomes 1 4 5
Following rule 1 the middle element 4 is deleted.
The list becomes 1 5
Following rule 2 The list becomes 6 5, (6=1+5)
After deleting 6 The list becomes 5.
Following rule 1 the middle element 5 is deleted.
Finally the list is NULL.

我的代码是

 #include <stdio.h>
 #include<stdlib.h>
 struct node
 {
     int data;
     struct node *next;
 }*head=NULL,*head1=NULL;
 //insertion into the linked list
 struct node* insert_at_tail(int data,struct node *he)
 {
     struct node *newn=(struct node*)malloc(sizeof(struct node));
     newn->data=data;
     newn->next=NULL;
     if (he==NULL)
        he=newn;
     else
     {
         struct node *temp=(he);
         while (temp->next!=NULL)
         {
           temp=temp->next;
         }
        temp->next=newn;
     }

      return he;
  }
  //printing the linked list
  void print(struct node *h2)
  {
   while(h2!=NULL)
    {

        printf("%d ",h2->data);
        h2=h2->next;
     }
   }

 void sol(int n,struct node *h)
 {
   head1=(struct node*)malloc(sizeof(struct node));
   head1=NULL;
   while(n>=0){
    struct node *temp=h;
    if(n%2==1){
        if(n==0){
            head1=insert_at_tail(temp->data,head1);
            free(temp);
        }
        else{
        for(int i=0;i<n/2;i++){
            temp=temp->next;
        }
        temp->next=temp->next->next;
        head1=insert_at_tail(temp->next->data,head1);
        free(temp->next);
        n=n-1;
        }
    }
    else{
        if(n==1){
            head=head->next;
            head1=insert_at_tail(temp->data+temp->next->data,head1);
            n=n-1;
            free(temp);
        }
        else{
        for(int i=0; i<n/2-1;i++){
            temp=temp->next;
         }
        temp->next=temp->next->next;     
  head1=insert_at_tail(
          temp->next->data+temp->next->next->data,
       head1);
          free(temp->next);
          n=n-1;
         }
       }
     }



   }
  int main(void) 
  {
    head=(struct node *)malloc (sizeof(struct node));
    head=NULL;
    head1=NULL;
    int d,i,ch,n;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
     scanf("%d",&d);
      head=insert_at_tail(d,head);
    }
  sol(n,head);
  print(head1);
}

输出没有回应帮助我解决这个问题

0 个答案:

没有答案