用C语言再写一个读入数据生成链表并处理的程序:⚫从上述input.ifo文件读入人员信息,正向建立线性表,使用循环链表方式存储;⚫输出线性表各结点的值和在线性表的位置值到屏幕;⚫键盘输入编号值S,在线性表中查找到编号为S的结点并输出结点的值,包括名字和随机编号(需要测试查找到和查找不到两种情况);⚫键盘输入位置值M,从线性表中1号结点开始向后报数,将报M的结点从线性表中删除,并输出该结点的编号和初始位置;(提示:可以将按位置删除函数改造成一个新的删除函数,删除的同时返回指向下一个结点的指针值、被删除结点的值;初始位置的值,可以考虑在建立循环链表时保存到结点内)⚫从刚才被删除人的下一个人开始重复上述步骤,直至最后只剩下一个人为止;⚫输出最后剩余一个人的编号和在线性表的初始位置。
时间: 2024-02-03 20:12:39 浏览: 78
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char name[20];
int id;
struct Node *next;
} Node;
int createList(Node **head);
void printList(Node *head);
Node *searchNode(Node *head, int id);
Node *deleteNode(Node *head, int pos);
int main() {
Node *head = NULL;
int s, m;
int len = createList(&head);
printf("The list is:\n");
printList(head);
printf("Please input a id to search: ");
scanf("%d", &s);
Node *node = searchNode(head, s);
if (node == NULL) {
printf("Can't find the node.\n");
} else {
printf("The node is: %s, %d\n", node->name, node->id);
}
printf("Please input a position to delete: ");
scanf("%d", &m);
while (len > 1) {
head = deleteNode(head, m);
len--;
printf("Deleted node is: %s, %d, initial pos: %d\n", head->name, head->id, m);
printf("The list is:\n");
printList(head);
printf("Please input a position to delete: ");
scanf("%d", &m);
}
printf("The last node is: %s, %d, initial pos: %d\n", head->name, head->id, 1);
free(head);
return 0;
}
int createList(Node **head) {
FILE *fp;
if ((fp = fopen("input.info", "r")) == NULL) {
printf("Can't open file.\n");
exit(1);
}
Node *p = (Node *)malloc(sizeof(Node));
*head = p;
int len = 0;
while (fscanf(fp, "%s %d", p->name, &p->id) != EOF) {
len++;
p->next = (Node *)malloc(sizeof(Node));
p = p->next;
}
free(p);
fclose(fp);
p->next = *head; // make it a circular linked list
return len;
}
void printList(Node *head) {
Node *p = head;
int pos = 1;
do {
printf("Pos: %d, Name: %s, ID: %d\n", pos++, p->name, p->id);
p = p->next;
} while (p != head);
}
Node *searchNode(Node *head, int id) {
Node *p = head;
do {
if (p->id == id) {
return p;
}
p = p->next;
} while (p != head);
return NULL;
}
Node *deleteNode(Node *head, int pos) {
Node *p = head;
Node *prev = NULL;
int i = 1;
while (i < pos) {
prev = p;
p = p->next;
i++;
}
if (p == head) {
head = p->next;
}
prev->next = p->next;
free(p);
return prev->next;
}
```
阅读全文