【发布时间】:2017-04-30 22:05:31
【问题描述】:
我想创建一个链表数组,其中每个数组元素都是链表的一个节点。基本上,我想通过数组元素来索引一个链表。假设我们有一个数组 a[20],其中每个元素代表链表的一个节点。图片如下:-
我创建了一个链接列表,它将在其中接受输入并打印列表。但是,我需要帮助来用数组索引它。这是我的链表。
#include <stdio.h>
#include <stdlib.h>
int a[20];
typedef struct Node {
int data;
struct Node *next;
} Node;
void insert_beg_of_list(Node *current, int data);
void print_list(Node *current);
void insert_beg_of_list(Node *current, int data) {
//keep track of first node
Node *head = current;
while(current->next != head) {
current = current->next;
}
current->next = (Node*)malloc(sizeof(Node));
current = current->next;
current->data = data;
current->next = head;
}
void print_list(Node *current) {
Node *head = current;
current = current->next;
while(current != head){
printf(" %d ", current->data);
current = current->next;
}
}
int main() {
Node *head = (Node *)malloc(sizeof(Node));
head->next = head;
int data = 0 ;
int usr_input = 0;
int i;
int m;
scanf("%d", &usr_input);
for (i=0; i<usr_input; i++) {
scanf("%d", &data);
insert_beg_of_list(head, data);
}
printf("The list is ");
print_list(head);
printf("\n\n");
return 0;
}
举个例子:-
它现在做了什么:-
Input :- Number of elements = 5
Input :- Elements = 1 2 3 4 5
Output :- 1 2 3 4 5
我的期望:-
Input :-
Number of elements for a[0] = 4
Input for a[0] = 1 2 3 4
Number of elements for a[1] = 4
Input for a[1] = 2 3 5 4
Expected Output :-
a[0] = 1 2 3 4
a[1] = 2 3 5 4
这是带有数组元素的修改代码。我将数据存储在current [0]
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *current[20];
void insert_beg_of_list(Node *current[0], int data);
void print_list(Node *current[0]);
void insert_beg_of_list(Node *current[0], int data) {
//keep track of first node
Node *head = current[0];
while(current[0]->next != head) {
current[0] = current[0]->next;
}
current[0]->next = (Node*)malloc(sizeof(Node));
current[0] = current[0]->next;
current[0]->data = data;
current[0]->next = head;
}
void print_list(Node *current[0]) {
Node *head = current[0];
current[0] = current[0]->next;
while(current[0] != head){
printf(" %d ", current[0]->data);
current[0] = current[0]->next;
}
}
int main() {
Node *head = (Node *)malloc(sizeof(Node));
head->next = head;
int data = 0 ;
int usr_input = 0;
int i;
int m;
int j;
scanf("%d", &usr_input);
for (i=0; i<usr_input; i++) {
scanf("%d", &data);
insert_beg_of_list(head, data);
}
printf("The list is ");
print_list(head);
printf("\n\n");
return 0;
}
显示分段错误。
【问题讨论】:
标签: c arrays list data-structures linked-list