数列问题 , 经典的链表操作

本文介绍了一个基于链表的数据结构实现,包括创建链表、输出链表元素、删除偶数节点和删除奇数节点等功能,并通过递归的方式实现了特定算法求解过程。

 

 

 

 

int Node_Size ;

struct Node{
       int x ;
       Node *next ;
};

Node * make_list(int n){
     int i  , j ;
     stack<int> stk ;
     Node *before , *root ;
     root = before = (Node *)malloc(sizeof(Node)) ;
     before->x = 1 ;
     before->next = NULL ;
     Node_Size = 1 ;
     for(i = 2 ; i <= n ; i++){
         j = i ;
         while(j){
             stk.push(j % 10) ;
             j /= 10 ;
         }
         while(!stk.empty()){
              Node_Size++ ;
              Node *now = (Node *)malloc(sizeof(Node)) ;
              now->x = stk.top() ;
              now->next = NULL ;
              before->next = now ;
              before = now ;
              stk.pop() ;
         }
     }
     return root ;
}

void out(Node *root){
     Node * p ;
     p = root ;
     do{
        printf("%d->",p->x) ;
        p = p->next ;
     }while(p != NULL) ;
     puts("") ;
}

Node * delete_even(Node *List){
    Node *root  , * now , *before;
    root = before = List ;
    now = before->next ;
    while(before->next != NULL  && now->next != NULL){
        before->next = now->next ;
        before = now->next ;
        free(now) ;
        now = before->next ;
        Node_Size-- ;
    }
    if(now != NULL && now->next == NULL){
        before->next = NULL ;
        Node_Size-- ;
    }
    return  root ;
}

Node * delete_odd(Node *List){
    Node *root  , * now , *before;
    List = List->next ;
    root =  List ;
    Node_Size-- ;
    root = delete_even(root) ;
    return  root ;
}

int gao(int n){
    Node_Size = 0 ;
    Node * root = make_list(n) ;
    int k = 1 ;
    while(Node_Size > 1){
       // out(root) ;
       // cout<<Node_Size<<endl ;
        root = k? delete_even(root) : delete_odd(root) ;
        k ^= 1 ;
    }
    int ans = root->x ;
    free(root) ;
    return ans ;
}

class Test {
public:
    static int remain (int   n)
    {
        return gao(n);
    }
};
//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
int main()
{   
    cout<<Test::remain(0)<<endl;   
} 
//end //提示:自动阅卷结束唯一标识,请勿删除或增加。

  

转载于:https://www.cnblogs.com/liyangtianmen/p/3581129.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值