【问题标题】:C linkedlist removeLast using pointersC链表removeLast使用指针
【发布时间】:2018-06-14 01:34:21
【问题描述】:

我正在学习如何在 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)

感谢您的时间和帮助。

【问题讨论】:

    标签: c linked-list function-pointers singly-linked-list


    【解决方案1】:

    您将指向head 的指针传递给removeLast()(参数ptr)。在那个函数中你修改*ptr

    由于ptr指向head变量所在的内存位置,修改*ptr会修改head的内容。由于head 的内容被函数调用修改了,所以它在函数返回后并不指向实际的列表头。

    为避免这种情况,您应该在 removeLast() 中使用单独的局部变量来遍历列表,并且仅在您确实要更改 head 时才修改 *ptr

    【讨论】:

    • 感谢您解决了我的问题,非常感谢您在 *ptr 修改 head 指针方面做得很好。我做了一个新的指针来遍历链接,它比你更有效,愿上帝保佑你有一群孩子。
    猜你喜欢
    • 2023-03-02
    • 1970-01-01
    • 2016-08-08
    • 2013-10-29
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多