【发布时间】:2021-11-17 00:46:18
【问题描述】:
编写一个包含整数链表的程序,允许您在列表中的 X 元素旁边复制 X 元素(X 由用户给出)。示例:列表:1,4,3,2,5,3,7; X=3。结果列表:1,4,3,3,2,5,3,3,7。
这就是我需要解决的问题,但我尝试了一切。链接列表是我无法想象的东西。我知道如何在结尾和开头添加一个数字,但在这个问题上我什至不知道从哪里开始。这就是我目前所拥有的:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int x;
struct node *next;
}Node;
// Check if the list is empty
int empty(Node *list){
if(list->next == NULL)
return 1;
else
return 0;
}
// Insert a number
void insert(Node *list){
Node *newn=(Node *) malloc(sizeof(Node));
printf("\nNumber: ");
scanf("%d", &newn->x);
newn->next = NULL;
if(empty(list))
list->next=newn;
else{
Node *aux = list->next;
while(aux->next != NULL){
aux = aux->next;
}
aux->next = newn;
}
}
// Print the list
void print(Node *list){
Node *next = list;
int i=1;
printf("\n");
if(empty(list)){
printf("EMPTY!\n");
}else{
list = list->next;
while(list!=NULL){
printf("NUMBER [%2d]: %d\n", i++, list->x);
list = list->next;
}
}
}
// Duplicate X values in the list
void duplicate(Node *lista){
}
int main(void) {
Node *list = (Node*)malloc(sizeof(Node));
int op, val;
do{
printf("\n1 - Insert\n");
printf("2 - Print\n");
printf("3 - Duplicate X\n");
printf("5 - Close\n");
printf("OPERATION: ");
scanf("%d", &op);
switch(op){
case 1:
insert(list);
break;
case 2:
print(list);
break;
case 3:
duplicate(list);
break;
case 5:
printf("Closed!\n");
break;
default:
printf("Invalid option!\n");
}
}while(op != 5);
return 0;
}
【问题讨论】:
-
对理解链表有很大帮助的一件事是把它们画出来。很多框(节点)和箭头(指针)。
-
list:
1,4,3,2,5,3,7==>1,4,3 break list here (virtually) 2,5,3,7,将3添加到第一个列表的末尾,相同的3添加到第二个列表的开头:- ) -
Invalid option\n应该打印到标准错误。但是,如果用户输入A作为选项,您的程序会如何表现?您应该检查scanf返回的值,并消耗坏数据而不是进入循环重复发出错误消息。
标签: c linked-list