【发布时间】:2020-08-30 17:17:00
【问题描述】:
我正在尝试在链表的“第 n 个”节点中添加一个值。如果 n = 0,则该值将是列表的头部。如果 n 大于列表的长度,它将是列表中的最后一个节点。否则,n 将被插入到列表中。但是,我的代码不起作用。下面是我的代码中访问任何输入并相应调整输入列表的函数。
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct node {
struct node *next;
int data;
};
struct node *insert_nth(int n, int value, struct node *head);
struct node *strings_to_list(int len, char *strings[]);
void print_list(struct node *head);
// DO NOT CHANGE THIS MAIN FUNCTION
int main(int argc, char *argv[]) {
int n;
scanf("%d", &n);
int value;
scanf("%d", &value);
// create linked list from command line arguments
struct node *head = NULL;
if (argc > 1) {
// list has elements
head = strings_to_list(argc - 1, &argv[1]);
}
struct node *new_head = insert_nth(n, value, head);
print_list(new_head);
return 0;
}
// Insert a new node containing value at position n of the linked list.
// if n == 0, node is inserted at start of list
// if n >= length of list, node is appended at end of list
// The head of the new list is returned.
struct node *insert_nth(int n, int value, struct node *head) {
struct node *temporary = head;
struct node *p;
p = malloc(sizeof(struct node));
p->data = value;
int count = 0;
while (temporary != NULL) {
count++;
temporary = temporary->next;
}
if (n == 0) {
p->next = head;
return p;
}
else if (n >= count) {
while (temporary != NULL) {
temporary = temporary->next;
}
temporary->next = p;
p->next = NULL;
return head;
}
else {
int i = 0;
while (i < count && temporary != NULL) {
temporary = temporary->next;
}
temporary = p;
p->next = temporary;
return head;
}
}
// DO NOT CHANGE THIS FUNCTION
// create linked list from array of strings
struct node *strings_to_list(int len, char *strings[]) {
struct node *head = NULL;
int i = len - 1;
while (i >= 0) {
struct node *n = malloc(sizeof (struct node));
assert(n != NULL);
n->next = head;
n->data = atoi(strings[i]);
head = n;
i -= 1;
}
return head;
}
// DO NOT CHANGE THIS FUNCTION
// print linked list
void print_list(struct node *head) {
printf("[");
struct node *n = head;
while (n != NULL) {
// If you're getting an error here,
// you have returned an invalid list
printf("%d", n->data);
if (n->next != NULL) {
printf(", ");
}
n = n->next;
}
printf("]\n");
}
【问题讨论】:
-
您能否提供一个完整的示例,其中包含
main程序发出您的insert_nth以重现您的问题?顺便说一句:当您写“它不起作用”时,您的实际意思是什么?它崩溃了吗?它破坏了数据?什么? -
我试图包含整个程序,但我无法发布它,因为显然代码太多了。不过我会再试一次。我的意思是它没有通过我的大部分练习测试。
标签: c struct linked-list insert singly-linked-list