【发布时间】:2021-05-01 06:37:02
【问题描述】:
我正在尝试制作从第一个节点删除的链表代码。我创建了一个结构 a
struct node{
int data;
struct node *next;
};
然后添加一些节点,不使用头指针,这里是我的主要
int main(){
struct node *first = malloc(sizeof(struct node));
struct node *second = malloc(sizeof(struct node));
struct node *third = malloc(sizeof(struct node));
struct node *forth = malloc(sizeof(struct node));
first->data = 1; //assing data in first node
first -> next = second; // link first node with second node
second -> data = 2;
second -> next = third;
third -> data = 3;
third -> next = forth;
forth -> data = 4;
forth->next = NULL;
printList(first);
// deletefromBeg(first);
//printList(first);
}
这是我打印列表的 printList 代码
void printList(struct node *n){
while (n != NULL){
printf("%d\n",n->data);
n = n -> next;
}
}
但是这个删除代码不起作用。我只想删除我的第一个节点,然后列表从第二个开始。
void deletefromBeg(struct node *first){
struct node *temp;
temp = first;
first = first->next;
printf("%d",temp->data);
free(temp);
}
【问题讨论】:
-
您想要
printList(second),因为first不再是列表的一部分。但无论如何,我会写一个合适的InsertList或AppendList或任何允许您将 en 元素正确添加到列表的函数,
标签: c pointers singly-linked-list pass-by-value function-definition