簡體   English   中英

在鏈表中使用遞歸

[英]Using recursion in linked list

新來的。 所以,我能夠弄清楚如何遍歷 A 中的每個元素並將其與 B 中的一個元素進行比較。 如果元素不匹配,則將該元素存儲到另一個列表中,並遞歸調用該函數到列表中的下一個節點A. 明顯的問題是它會將 A 中的所有元素與 B 中的第一個元素進行比較。但是我在如何遞歸訪問 B 中的下一個元素或節點以返回包含值的新集合方面遇到困難不在集合 B 中的集合 A。

是的,列表已排序。

Node *diff(Node *a, Node *b) {

    Node *tmp;
    tmp = malloc(sizeof(Node));

    if ( (a == NULL) || (b == NULL) )   //Base case
            return NULL;

    if (a->val != b->val){
            tmp = a;
            tmp->next = sset_diff(a->next, b);
    }

    return tmp;


 return NULL;  //Placeholder
}

(特別是)在使用遞歸時,確定您的子任務很重要。 在這里編寫另一個函數來檢查一個值是否是列表的成員是有意義的:

is_member(int val,Node *list) { //I'm assuming that it's a list of int
    if (list==NULL) return 0;
    if (list->val==val) return 1;
    return is_member(val,list->next);
}

之后,您可以輕松創建 A 中值的列表,而 B 中不存在這些值:

Node *diff(Node *a, Node *b) {
    if (a==NULL) return NULL; //the correct base case
    if (is_member(a->val,b)) return diff(a->next,b); //deal with one case
    Node *tmp=malloc(sizeof(Node)); //allocate it only now
    tmp->val=a->val; //assign to the value, not to the Node*
    tmp->next=diff(a->next,b); //the next elements
    return tmp;
    //there is not need to return NULL here
}

你必須使用遞歸嗎? 使用循環可能更容易做到這一點,例如:

Node *b2;//Make this variable so you can reset b after first while loop exits
b2 = b;
while(a != NULL) {
    while(b != NULL) {
        if (a->val != b->val) {
            tmp = a;
            tmp->next = NULL;
        }
        b = b->next;
    } //End inner while loop
    a = a->next;
    b = b2;
}//End outter while loop

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM