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;
}