數據結構:單向鏈表系列5--在鏈表中查找元素


在鏈表中查找元素

函數簽名:

bool search(Node *head, int x) 

如果在鏈表中查找到這個元素返回true,否則false

迭代法

2) 初始化一個節點指針, current = head.
3) 如果current不為NULL執行以下循環
    a) current->key 等於當前待查找值key則返回true.
    b) current = current->next
4) 否則返回 false 
/*Checks whether the value key is present in linked list*/
bool search(struct Node* head, int key)
{
    struct Node* current = head; //Initialize current

    while(current != NULL) { if(current->data == key) return true; current = current->next; } return false; }

java:

  //Checks whether the value key is present in linked list 
    public boolean search(Node head, int key) 
    { 
        Node current = head;    //Initialize current 
        while (current != null) { if (current.data == key) return true; //data found current = current.next; } return false; //data not found }

c#

  // Checks whether the value key is present in linked list 
    public bool search(Node head, int key) 
    { 
        Node current = head; // Initialize current 
        while (current != null) { if (current.data == key) return true; // data found current = current.next; } return false; // data not found } 

 

遞歸法:

bool search(head, x)
1)如果head是NULL, return false.
2) 如果head數據域的值和待查找的一致,返回true;
2) 否則返回 search(head->next, x) 

c語言:

/*
    Checks whether the value key is present in linked list
 */
bool searchRecursive(struct Node* head, int key)
{
    if(head == NULL) { return false; } //If key is present in current node, //return true if(head->data == key) return true; //recursive for remaining list return searchRecursive(head->next, key); }

 java:

  // Checks whether the value key is present 
    // in linked list 
    public boolean search(Node head, int key) 
    { 
        // Base case 
        if (head == null) return false; // If key is present in current node, // return true if (head.data == key) return true; // Recur for remaining list return search(head.next, key); } 

c#

// Checks whether the value key is present 
    // in linked list 
    public bool search(Node head, int key) 
    { 
        // Base case 
        if (head == null) return false; // If key is present in current node, // return true if (head.data == key) return true; // Recur for remaining list return search(head.next, key); } 

 文章來源:https://www.geeksforgeeks.org/search-an-element-in-a-linked-list-iterative-and-recursive/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM