单链表的查找(按位查找和元素查找)

目录

1.单链表的按照位序查找

2.单链表的按照元素查找


单链表的按照位序查找

1.按位序查找的函数结构:

LNode *LocateNode(LinkList LL, unsigned ii)

        函数定义采用的是自己定义的链表结构体LNode,因为在此处找到之后返回的是该结点的地址,所以采取指针形式。函数的参数有两个,第一个参数是完整单链表的地址,第二个是所要查找的结点位序。

2.函数的代码:

LNode *LocateNode(LinkList LL, unsigned ii){
	if(LL == NULL){
		printf("该链表不存在!");
	}
	
	LNode *pp=LL;
	int kk=0;
	while(pp != NULL && kk<ii){
		pp=pp->next;
		kk++;
	}
	
	if(pp==NUll){
		printf("该位置不合法,已经超过了表长!");
	}
	return pp;
} 

该查找方法思路较为简单,主要分为三块:1.判断链表是否存在,2.寻找索访问结点的位置,3.判断该位置是否越界,若未越界,则返回该结点位的地址。


单链表的按结点查找

1.函数的结构形式:LNode *LocateElem(LinkList LL, ElemType *ee)。第一个参数依旧是链表的地址,第二个参数是所要查找元素的地址(考虑到会有结构体的情况,所以参数采用地址的形式。)

2.函数的代码

LNode *LocateElem(LinkList LL, ElemType *ee){
	if(LL == NULL){
		printf("该链表不存在!");
		return NULL;
	}
	
	LNode *pp;
	*pp = LL->next;        //记住要从第一个结点开始计算
	while(pp != NULL){
		if(pp->data == *ee)
			return pp;     //如果找到了,就返回地址 
			
		pp = pp->next	   //未找到,则指针后移 
	} 
	
	return NULL;          //若元素不存在,则返回NULL。 
}

 该函数的思路较为简单,有注释即可。

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
链表的按位查找是指根据给定的位置,查找链表中对应位置的节点。以下是链表按位查找的完整代码示例: ```cpp #include <iostream> using namespace std; // 定义链表节点结构 struct ListNode { int data; // 节点数据 ListNode* next; // 指向下一个节点的指针 }; // 按位查找链表节点 ListNode* findNodeByPosition(ListNode* head, int position) { if (head == nullptr || position <= 0) { return nullptr; } ListNode* current = head; int count = 1; while (current != nullptr && count < position) { current = current->next; count++; } return current; } // 创建链表 ListNode* createLinkedList(int n) { if (n <= 0) { return nullptr; } ListNode* head = nullptr; ListNode* tail = nullptr; for (int i = 1; i <= n; i++) { ListNode* newNode = new ListNode(); newNode->data = i; newNode->next = nullptr; if (head == nullptr) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } } return head; } // 打印链表 void printLinkedList(ListNode* head) { ListNode* current = head; while (current != nullptr) { cout << current->data << " "; current = current->next; } cout << endl; } int main() { int n; // 链表长度 int pos; // 查找位置 cout << "请输入链表长度:"; cin >> n; ListNode* head = createLinkedList(n); cout << "请输入要查找的位置:"; cin >> pos; ListNode* result = findNodeByPosition(head, pos); if (result != nullptr) { cout << "查找结果为:" << result->data << endl; } else { cout << "查找失败,位置超出链表长度!" << endl; } return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值