我正在尝试编写一个简单的循环链接列表程序,我想在开始时插入节点。
1:首先我创建了列表。 2:然后我想在开头插入元素。
当我试图输出它的显示时,元素被插入第一个元素之后,这是我不期望的。
如果有人面对同样的问题但没有取得丰硕成果,我试了很多帖子。有人可以帮我这个..
#include<stdio.h>
#include<stdlib.h>
typedef struct llist
{
int data;
struct llist *next;
}list;
void createlist(list**, int);
void InsertAtbeg(list**, int);
void display(list*);
int main()
{
list *node = NULL;
int i,n;
printf("\n enter no of elements:-");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
createlist(&node, i);
}
display(node);
InsertAtbeg(&node, 100);
printf("\n elements after insertion at beg :-");
display(node);
return 0;
}
void createlist(list **H, int x)
{
list *p,*r;
if(*H==NULL)
{
p = (list*)malloc(sizeof(list));
p->data =x;
p->next = p;
*H = p;
}
else
{
r = (list*)malloc(sizeof(list));
r ->data =x;
p->next =r;
r->next =*H;
p=r;
}
}
void InsertAtbeg(list**H, int x)
{
list* p,*r;
r=*H;
p= (list*)malloc(sizeof(list));
p->data =x;
p->next = r->next;
r->next = p;
*H=r;
}
void display(list* H)
{
list *p;
if(H!=NULL)
{
p = H;
while (p->next != H)
{
printf("\n elements in list are:- %d", p->data);
p = p->next;
}
printf("\n elements in list are:- %d", p->data);
}
}
答案 0 :(得分:1)
您将使InsertAtbeg
返回添加的新节点并将其设置为头部并将其传递给display
。相反,你正在做的是传递旧头,这显然是不正确的。
添加所需的标题
#include<stdio.h>
#include<stdlib.h>
您的createlist
不合适(我没有检查它,但在for
内写了一个快速main
循环。
int main() {
list *head = malloc(sizeof(list));
list *node = head;
int i,n;
printf("\n enter no of elements: ");
scanf("%d",&n);
for (i=1;i<=n;i++) {
node->data = i;
if (i<n) {
node->next = malloc(sizeof(list));
node = node->next;
} if (i==n)
node->next = head;
}
display(head);
list* I = InsertAtbeg(node, 100);
printf("\n elements after insertion at beg :-");
display(I); // here you need to pass the new node "I" as head
return 0;
}
现在InsertAtBeg
您实际上可以通过last
节点而不是head
。您可以从last->next
获取头部,并返回新的head
。
list* InsertAtbeg(list *Last, int x) {
list *Head = Last->next;
list *Insert = malloc(sizeof(list));
Last->next = Insert;
Insert->data = x;
Insert->next = Head;
return Insert;
}
显示功能我原样保留了它。
答案 1 :(得分:1)
以下是您的代码的副本。我添加了评论来解释错误。
void InsertAtbeg(list**H, int x)
{
list* p,*r;
r=*H;
p= (list*)malloc(sizeof(list));
p->data =x;
p->next = r->next; // wrong: must be p->next = r as the new element
// shall point to the current head
r->next = p; // wrong: delete this line - no need for changing
// next of current head
*H=r; // wrong: must be *H = p so the new element becomes head
// wrong: you are not done yet. you miss that the last element
// shall have its next pointer updated
// so that it points to the new element
}
BTW:由于p未初始化,您的createlist
具有未定义的行为