链表查找算法
链表查找:实现以节点nodes方式串联起来的链表,每个节点包含一份数据,以及一个指向下一个节点的指针。
(一)C实现链表查找:
C语言节点数据结构
struct
};
bool operator==(const int_node& node,int n){return node.val==n;}
遍历链表:
int_node* p;
for(p=list_head; p!=NULL;p->next){//做某些事情}
(二)C++实现链表查找:
定义一个链表节点数据包:
template <class Node>
struct node_wrap{
Node* ptr; //定义节点指针
node_wrap(Node* p=0):ptr(p){}
Node& operator*() const{return
Node* operator->() const{return ptr;}
node_wrap& operator++(){ptr=ptr->next;return *this;} //指向下个节点的指针(前置累加)
node_wrap
bool operator==(const node_wrap& i) const{return ptr==i.ptr;} //判断是否是同一地址的节点指针
bool operator!=(const node_wrap& i)const{return ptr!=i.ptr;} //判断是否不是同一地址的节点指针
};
查找链表节点int_node中具有某个特定的值(无需写循环),可以重复利用find,将查找动作写成单一函数调用:find(链表头,链表尾,节点值)
find(node_wrap<int_node>(list_head) ,node_wrap<int_node>(),val)
其中,链表尾node_wrap<int_node>()是利用node_wrap的默认构造函数作出,它产生一个内含NULL指针的node_wrap,而链表尾最后一个节点的next指针即为NULL。