算法导论-第十章课后题

10.2.7

给出一个O(n)时间的非递归过程,实现一个含n个元素的单链表的逆转。要求除存储链表本身的所需空间外,该过程只能使用固定大小的空间。

public Nodereverse(Node data){
    Node new_node = null;
    while(data != null){
        Node next = data.next;
        data.next = new_node;
        new_node = data;
        data = next;
    }    
    return new_node;
}

10.2.8

说明每个元素在只使用一个指针x.np的情况下实现双向链表。假如所有的值都可视为k位的整型值,且定义x.np = x.pre xor x.next,NIL用0。实现search、insert、delete。并在o(1)的时间实现逆转。

 伪代码

//搜索
search(l,k){
    p = NIL
    x = l.head;
    while(x != null && x.key != k){
        tmp = x;
        x = p xor x ; 
        p = tmp
    }
}

//插入
insert(l,x){
    x.np = l.head; 
    l.nil.np = x xor l.nil.np xor l.head.np;
    l.head = x;
}

//删除
delete(l,x){
 l.nil.np = l.nil.np xor l.head xor l.head.np;
 l.head.np.np = l.head xor l.head.np.np 
}

//逆序
reverse(l){
 l.head = l.nil.np xor l.head;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值