向列表中添加元素的代码不完整。
我使用双链表在c.中保存4个不同的记录
我在为双链接列表创建空间时遇到问题。当我尝试添加2个以上的节点时,我会丢失除第一个节点之外的所有节点,并且我会看到第一个和最后一个节点的数据。我看不到从第二个到最后一个的节点。我尝试更改节点之间的链接,但没有成功。这是我的密码;
struct node {
char name[100];
char surname[100];
char roll[100];
char department[100];
struct node *next;
struct node *prev;
};
struct node *first_oto = NULL, *last_oto = NULL, *l;
void insert() {
int i, counter = 1;
first_oto = (struct node*)malloc(sizeof(struct node));
first_oto->prev = NULL;
first_oto->next = NULL;
printf(" %d- Name:", counter);
scanf("%s", first_oto->name);
printf(" %d-Surname", counter);
scanf("%s", first_oto->surname);
printf(" %d-Number", counter);
scanf("%s", first_oto->roll);
printf(" %d-Department", counter);
scanf("%s", first_oto->department);
first_oto->next = NULL;
for (i = 1; i < n; i++) {
counter++;
l = (struct node*)malloc(sizeof(struct node));
printf(" %d-Name:", counter);
scanf("%s", l->name);
printf(" %d-Surname:", counter);
scanf("%s", l->surname);
printf(" %d-Number:", counter);
scanf("%s", l->roll);
printf(" %d-Department:", counter);
scanf("%s", l->department);
printf("n");
l->next = NULL;
l->prev = first_oto;
first_oto->next = l;
}
在插入函数的第一部分中,我的代码记录了第一个节点。当我的程序为循环操作时,它会占用其他节点,但只添加最后一个节点。我该怎么修?
l->next=NULL;
l->prev=first_oto;
first_oto->next=l;
/* There's another thing you need to do right here. */
}
应该有一个临时变量来添加情境。
struct node *temp;
在分配l->next=NULL
后的for循环中,我们必须为temp添加一些代码粒子。我们将第一个元素保留为temp,并使用temp变量以避免数据丢失。
在下面的代码中,我们做到了。
temp = (struct node*)malloc(sizeof(struct node));
temp = first_oto;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next = l;
l->prev = temp;
last_oto = l;
写完这几行字,问题就解决了。
试试这个
void insert(void)
{
struct node *new_node, *temp;
char ans = 'y';
int pos;
do {
traverse();
printf("Enter the element :n");
new_node = (struct node*)malloc(sizeof(struct node));
scanf("%d", &new_node->info);
new_node->next = NULL;
new_node->prev = NULL;
if (start == NULL) {
start = new_node;
current = new_node;
} else {
printf("Enter the position at which u wanna enter : (1-%d)n", count + 1);
scanf("%d", &pos);
if (pos == 1) {
start->prev = new_node;
new_node->next = start;
start = new_node;
} else
if (pos == count + 1) {
current->next = new_node;
new_node->prev = current;
current = new_node;
} else {
int i = 0;
temp = start;
while (i < pos - 2) {
temp = temp->next;
i++;
}
new_node->prev = temp;
new_node->next = temp->next;
temp->next = new_node;
}
}
printf("Wanna enter more ??n");
scanf(" %c", &ans);
} while (ans == 'y' || ans == 'Y');
}