python 單鏈表查詢元素 在單鏈表中搜尋

2021-10-12 11:04:14 字數 2347 閱讀 5582

執行搜尋以便在鍊錶中找到指定元素的位置。 搜尋鍊錶中的任何元素都需要遍歷列表,並將列表的每個元素與指定的元素進行比較。 如果元素與任何鍊錶中的元素匹配,則從函式返回元素的位置。

演算法第1步:設定ptr = head

第2步:設定i = 0

第3步:如果ptr = null

提示「空列表,沒有什麼可以搜尋」

轉到第8步

結束if條件

第4步:重複第5步到第7步直到ptr!= null

第5步:如果ptr→data = item

寫入 i + 1

結束if條件

第6步:i = i + 1

第7步:ptr = ptr→next

[迴圈結束]

第8步:退出

c語言示例** -

#include

#include

void create(int);

void search();

struct node

int data;

struct node *next;

struct node *head;

void main()

int choice, item, loc;

doprintf("1.create\n");

printf("2.search\n");

printf("3.exit\n");

printf("4.enter your choice ? ");

scanf("%d", &choice);

switch (choice)

case 1:

printf("enter the item\n");

scanf("%d", &item);

create(item);

break;

case 2:

search();

case 3:

exit(0);

break;

default:

printf("please enter valid choice\n");

} while (choice != 3);

void create(int item)

struct node *ptr = (struct node *)malloc(sizeof(struct node *));

if (ptr == null)

printf("overflow\n");

else

ptr->data = item;

ptr->next = head;

head = ptr;

printf("node inserted\n");

void search()

struct node *ptr;

int item, i = 0, flag;

ptr = head;

if (ptr == null)

printf("empty list\n");

else

printf("enter item which you want to search?\n");

scanf("%d", &item);

while (ptr != null)

if (ptr->data == item)

printf("item found at location %d ", i + 1);

flag = 0;

else

flag = 1;

i++;

ptr = ptr->next;

if (flag == 1)

printf("item not found\n");

執行上面示例**,得到以下結果 -

1.create

2.search

3.exit

4.enter your choice?1

enter the item

node inserted

1.create

2.search

3.exit

4.enter your choice?1

enter the item

node inserted

1.create

2.search

3.exit

4.enter your choice?2

enter item which you want to search?

item found at location 1

¥ 我要打賞

糾錯/補充

收藏加qq群啦,易百教程官方技術學習群

注意:建議每個人選自己的技術方向**,同乙個qq最多限加 3 個群。

查詢單鏈表中間元素

查詢單鏈表中間元素 include using namespace std struct linknode class linklist linklist void insertvalue int nvalue void reverse void reverse2 linknode findlast...

單鏈表元素定位

6 2 單鏈表元素定位 12 分 本題要求在鍊錶中查詢第乙個資料域取值為x的節點,返回節點的位序。l是乙個帶頭結點的單鏈表,函式listlocate l linklist l,elemtype x 要求在鍊錶中查詢第乙個資料域取值為x的節點,返回其位序 從1開始 查詢不到則返回0。例如,原單鏈表各個...

3 單鏈表內元素的查詢

演算法功能 按序號或按值查詢單鏈表中的元素 演算法思路 由於單鏈表是非順序儲存結構,元素之間通過指標來描述邏輯結構,因而無法實現隨機訪問,查詢過程只能是 順鏈掃瞄。若查詢單鏈表中第i個元素,則要從單鏈表的第乙個結點開始,用p做標記指標,j做計數器,順序掃瞄鍊錶。當p不為空,而且 j i 時,指標p所...