【单链表的“按值查找”算法代码】

#include <bits/stdc++.h>
using namespace std;

struct LNode {
    char data;
    LNode *next;
};
typedef struct LNode *LinkList;

void Tail_Insert(LinkList &L, int n) {
    L=new LNode;
    L->next=NULL;
    LinkList r=L;

    for(int i=0; i<n; i++) {
        LinkList p=new LNode;
        cin>>p->data;
        p->next=NULL;
        r->next=p;
        r=p;
    }
}

//按值查找:返回首次出现的位置(从1开始),未找到返回0
int Find_By_Value(LinkList L, char val) {
    LinkList p=L->next;
    int pos=1;
    while(p) {
        if(p->data==val) {
            return pos;
        }
        p=p->next;
        pos++;
    }
    return 0;
}

void Print_List(LinkList L) {
    LinkList p=L->next;
    while(p) {
        cout<<p->data<<" ";
        p=p->next;
    }
    cout<<endl;
}

int main() {
    int n,pos;
    char val;
    LinkList L;

    cin>>n;
    Tail_Insert(L,n);
    //Print_List(L);

    cin>>val;
    int foundPos=Find_By_Value(L,val);
    if(foundPos) cout<<foundPos<<endl;
    else cout<<"Not found"<<endl;

    return 0;
}



/*
in:
5
a b c d e
c

out:
3
*/





 

更多推荐