c语言用尾插法实现链表建立并实现按序号查询,删除信息输出链表功能
时间: 2023-05-20 19:05:55 浏览: 124
C语言尾插法建立链表并正序输出建立正序链表.zip
可以使用以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList(int n);
void printList(Node *head);
Node *deleteNode(Node *head, int index);
int main() {
int n, index;
Node *head = NULL;
printf("Enter the number of nodes: ");
scanf("%d", &n);
head = createList(n);
printf("Enter the index of the node to be deleted: ");
scanf("%d", &index);
head = deleteNode(head, index);
printf("The final list is:\n");
printList(head);
return 0;
}
Node *createList(int n) {
Node *head = NULL, *tail = NULL;
for (int i = 1; i <= n; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
printf("Enter the data for node %d: ", i);
scanf("%d", &newNode->data);
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
Node *deleteNode(Node *head, int index) {
Node *p = head, *q = NULL;
if (index == 1) {
head = head->next;
free(p);
} else {
for (int i = 1; i < index; i++) {
q = p;
p = p->next;
}
q->next = p->next;
free(p);
}
return head;
}
```
这个程序使用尾插法创建了一个链表,并实现了按序号删除节点的功能。
阅读全文