Chapter 10 Exercises

Exercises
10.1-7 Show how to implement a queue using two stacks. Analyze the running time of the queue operations.
The amortized time is still O(1) each operation.
DATA_TYPE Enqueue(DATA_TYPE data)
... {
    Stack1.Push(data);
}

DATA_TYPE Dequeue(DATA_TYPE data)
... {
   
if(Stack2.Empty())
       
while(!Stack1.Empty())
            Stack2.Push(Stack1.Pop());
   
return Stack2.Pop();
}

Since each data is pushed and poped in stack1 and stack2 once respectively, the amortized time is O(1). However, the DEQUEUE operation may have an O(n) worst-case time in the case that stack2 is empty and stack1 is full.

10.2-8 Explain how to implement doubly linked lists using only one pointer value np[x] = next [x] XOR prev[x]. Also show how to reverse such a list in O(1) time.
Store two adjacent nodes in the list, say they're x and x->next(x and x->next are all pointers to nodes)
Then x->next->next = x->next->np[x] XOR x
Through performing NEXT operation in O(1) time (and vice versa for PREV operation), all the properties which ordinary linked lists have also apply to this special list.
However, to reverse such a list, we can just change the position of x and x->next which are stored. i.e. let x->next be the new "x" and x be the new "x->next". The new NEXT operation is thus equivalent to the original PREV operation (and vice versa). This is the O(1) reverse algorithm.

10.4-6 Show how to use only two pointers and one boolean value in each node so that the parent of a node or all of its children can be reached and identified in time linear in the number of children.
Use the IsLastChild boolean field instead of parent pointer field, reserving the other two pointer fields(left-child and right-sibling). It's easy to perform PARENT operation in O(n) time if we let the right-sibling field of the node which is the last child(IsLastChild == true) , be the pointer to the parent. Then we can merely traverse to the last child, and call right- sibling again to access the parent of the siblings.

转载于:https://www.cnblogs.com/FancyMouse/articles/1056799.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值