簡體   English   中英

數據結構單循環列表

[英]Data structures singly circular linked list

這是我的單鏈接列表代碼:

void addtoempty(int data)
{
    if (last->next == NULL)
    {
        struct node* new_node = malloc(sizeof(struct node));
        new_node->data = data;
        last->next = new_node;
        new_node->next = new_node;
    }
    else
    {
        printf("element exists\n");
    }
}

void insert(int data)
{
    if (last->next == NULL)
        addtoempty(data);
    else
    {
        // intf("now insert vl happen\n");
        struct node* new_node = malloc(sizeof(struct node));
        new_node->data = data;
        new_node->next = last->next;
        last->next->next = new_node;
        last->next = new_node;
    }
}

void display()
{
    print = last->next->next;
    do
    {
        printf("%d \t", print->data);
        print = print->next;
    } while (print != last->next->next);
    printf("\n");
}

我想僅使用尾指針在單循環鏈表中的節點后插入元素。 可能嗎? 如果是,怎么辦? 並且在上述程序中,應該對insert()進行哪些更改以實現上述結果?

問題出在insert 您將設置三個next指針:

new_node->next = last->next;
last->next->next = new_node;
last->next = new_node;

您應該只設置兩個:

new_node->next = last->next;
last->next = new_node;

第三個設置了last->next->next ,實際上刪除了列表的其余部分。

暫無
暫無

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

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