簡體   English   中英

C鏈表removeLast使用指針

[英]C linkedlist removeLast using pointers

我正在學習如何在c中創建鏈表,但遇到了一個無法解決的問題。 我的鏈表的removeLast(link * ptr)方法遇到問題,我相信它與指針的使用有關,但是我真的不明白為什么程序無法從列表中刪除倒數第二個元素,不知何故我的名單被銷毀了。 這是我的代碼:

#include <stdio.h>
#include <stdlib.h>

// typedef is used to give a data type a new name
typedef struct node * link ;// link is now type struct node pointer

/*
    typedef allows us to say "link ptr"
    instead of "struct node * ptr"
*/

struct node{
    int item ;// this is the data
    link next ;//same as struct node * next, next is a pointer
};

//prints the link
void printAll(link ptr){
    printf("\nPrinting Linked List:\n");
    while(ptr != NULL){
        printf(" %d ", (*ptr).item);
        ptr = (*ptr).next;// same as ptr->next
    }
    printf("\n");
}

//adds to the head of the link
// link * ptr so that we may modify the head pointer
void addFirst(link * ptr, int val ){
    link tmp = malloc(sizeof(struct node));// allocates memory for new node
    tmp->item = val;
    tmp->next = * ptr;
    * ptr = tmp;
}

// removes and returns the last element in the link
// link * ptr so that we may modify the head pointer
link removeLast(link * ptr){

    if(ptr == NULL) return NULL;

    // traverse the link
    link prev = NULL;// prev is pointer
    while((*ptr)->next != NULL){
        prev = *ptr;
        *ptr = (*ptr)->next;
    }

    // if only one node on list
    if(prev == NULL){
        link tmp = malloc(sizeof(struct node));// allocates memory for new node
        tmp = *ptr;
        *ptr = NULL;
        return tmp;
    }

    // if more than one node
    prev->next = NULL;
    return *ptr;
}

// testing
int main(void) {

    link head = NULL;// same as struct node * head, head is a pointer type

    //populating list
    for(int i = 0; i<10; i++){
        addFirst(&head, i);// "&" is needed to pass address of head
    }

    printAll(head);

    while(head != NULL){
        link tmp = removeLast(&head);
        if(tmp != NULL)
            printf(" %d ", tmp->item);
    }

    return 0;
}

這是我的輸出:

    Printing Linked List:
     9  8  7  6  5  4  3  2  1 
    prev = 9
    prev = 8
    prev = 7
    prev = 6
    prev = 5
    prev = 4
    prev = 3
    prev = 2
     0  0 
    RUN SUCCESSFUL (total time: 136ms)

感謝您的時間和幫助。

您將指向head的指針傳遞給removeLast() (參數ptr )。 在該函數中,您可以修改*ptr

由於ptr指向head變量所在的內存位置,因此修改*ptr會修改head的內容。 由於head的內容由函數調用修改,因此在函數返回后,它不會引用列表的實際head。

為了避免這種情況,您應該在removeLast()使用單獨的局部變量來遍歷列表,並且僅在確實打算更改head時才修改*ptr

暫無
暫無

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

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