用C语言编写代码实现单链表的建立、输出、插入、删除、判断链表是否为空、输出链表长度,并且当输入1时为插入操作
时间: 2023-08-01 12:15:06 浏览: 100
C语言实现单链表,单链表操作
好,下面是用C语言实现单链表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
//定义链表结构体
struct ListNode {
int val;
struct ListNode *next;
};
//创建链表
struct ListNode* createList() {
struct ListNode *head = NULL;
struct ListNode *tail = NULL;
int val;
printf("请输入链表节点的值(输入-1结束):");
while (1) {
scanf("%d", &val);
if (val == -1) {
break;
}
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
//输出链表
void printList(struct ListNode *head) {
if (head == NULL) {
printf("链表为空!\n");
return;
}
printf("链表节点的值为:");
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
//插入节点
struct ListNode* insertNode(struct ListNode *head) {
int val, pos;
printf("请输入要插入的节点的值和插入位置:");
scanf("%d %d", &val, &pos);
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
if (pos == 1) {
node->next = head;
head = node;
} else {
struct ListNode *pre = head;
for (int i = 1; i < pos - 1; i++) {
pre = pre->next;
}
node->next = pre->next;
pre->next = node;
}
return head;
}
//删除节点
struct ListNode* deleteNode(struct ListNode *head) {
int val;
printf("请输入要删除的节点的值:");
scanf("%d", &val);
struct ListNode *pre = head;
if (head->val == val) {
head = head->next;
free(pre);
} else {
while (pre->next != NULL && pre->next->val != val) {
pre = pre->next;
}
if (pre->next == NULL) {
printf("要删除的节点不存在!\n");
} else {
struct ListNode *del = pre->next;
pre->next = del->next;
free(del);
}
}
return head;
}
//判断链表是否为空
int isEmpty(struct ListNode *head) {
return head == NULL;
}
//输出链表长度
int length(struct ListNode *head) {
int len = 0;
while (head != NULL) {
len++;
head = head->next;
}
return len;
}
int main() {
struct ListNode *head = createList();
printList(head);
int op;
printf("请选择操作(1 插入节点,2 删除节点):");
scanf("%d", &op);
switch (op) {
case 1:
head = insertNode(head);
break;
case 2:
head = deleteNode(head);
break;
default:
printf("无效操作!\n");
}
printList(head);
printf("链表是否为空:%d\n", isEmpty(head));
printf("链表长度为:%d\n", length(head));
return 0;
}
```
以上代码实现了单链表的创建、输出、插入、删除、判断链表是否为空、输出链表长度,并且当输入1时为插入操作。
阅读全文