【问题标题】:circular link list insertion at beginning循环链表在开头插入
【发布时间】:2021-01-18 16:46:51
【问题描述】:

我在开头进行插入,但我的代码将其插入到最后。我正在考虑,但我认为我的逻辑是正确的。 我认为首先我创建一个指针 p 并将其初始化为 head 然后递增它直到它不等于 head 然后创建一个新链接。这是一个正确的方法吗?

来了,

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

typedef struct node{

    int data;
    struct  node *next;
        
}sll;

void traversal(sll* head){

    sll* p;
    p=head;
       
    do
    {
        printf("%d\n",p->data);
        p=p->next;
    }while (p!=head);
    
}

sll* insertionstart(sll* head,int data){

        sll* ptr=(sll*)malloc(sizeof(sll));
        ptr->data=data;
       
        sll* p=head;
         do
        {
           p= p->next;
    }   while (p->next!=head);
        
         p->next=ptr;
        ptr->next=head;
        
        return head;
        
        
}

int main(){
    sll* ptr;
    sll* head;
    sll* second;
    sll* third;
    sll* fourth;
    sll* fifth;

    

    head = (sll*) malloc(sizeof(sll));
    second = (sll*) malloc(sizeof(sll));
    third = (sll*) malloc(sizeof(sll));
    fourth = (sll*) malloc(sizeof(sll));
    fifth = (sll*) malloc(sizeof(sll));


    head -> data=56;
    head ->next=second;

    
    second -> data=3;
    second->next=third;

    
    third -> data=18;
    third ->next=fourth;

    
    fourth -> data=90;
    fourth ->next=fifth;

    fifth -> data=76;
    fifth ->next=head;

    traversal(head);
    printf("*******************\n");
    head=insertionstart(head,42);
    traversal(head);

    return 0;
}

【问题讨论】:

  • 先生,我认为在循环 ll 中第一个 p 转到最后一个元素 p->next =ptr 以便我增加它。
  • 要在开头插入,您必须有一些代码将head 指针更改为指向新节点。目前你的函数总是只返回旧的head
  • 先生,这里 p 增加了,p=head 也增加了头部
  • phead副本。更改 phead 没有影响。如果您不相信只需在调试器中运行您的程序并在程序运行时检查指针值。此外,如果它确实改变了head,那么p-&gt;next!=head 将毫无意义,因为head 会不断变化。
  • 是的,先生,如果我取下返回头,您现在就是这样,它会在开头打印。

标签: c linked-list insertion


【解决方案1】:

如果您希望新元素成为新头,只需在insertionstart 中进行此更改:

return head;  -->  return ptr;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多