在链表的末尾插入元素

inserting element at the end of linked list

本文关键字:插入 元素 链表      更新时间:2023-10-16

我试图在链表的末尾插入元素,但while循环不终止。我不明白为什么会发生这种事。这是我的代码。

我在main()函数中调用这个函数。

struct node{
    int data;
    struct node* link;
};
struct node * head;

void insert_last(int element){ 
    struct node * temp  = (node*)malloc(sizeof(struct node));
    temp->data = element;
    temp->link = NULL;
    if(head==NULL){
        head = temp;
    }
    struct node * temp1 = head;
    while(temp1->link!=NULL){
        temp1 = temp1->link;
    }
    temp1->link = temp;
}

下面是主要的方法:

int main()
{
    head = NULL;
    printf("Enter the no. of nodes or elements you want to make linked list of. ");
    int n;
    scanf("%d",&n);
    int element = 0;
    for(int i = 0; i<n; i++){
        printf("Enter the elementn");
        scanf("%d",&element);
        insert_last(element);
        std::cout<<"Element insertednn";
    }
    //print_recursive(head);
    print();
}

很简单。

if(head==NULL){
    head = temp;
}

在这种情况下,你已经完成了你正在做的事情。继续下去,temp1就变成了temp。然后temp1->link = temp;使这个节点指向自己。第二次插入将永远不会找到结束,因为您的列表现在是循环的,while(temp1->link!=NULL)将永远不会结束。

你应该做的就是把return; .

if(head==NULL){
    head = temp;
    return;
}