#define _CRT_SECURE_NO_WARNINGS 1
#include "stdio.h"
#include "stdlib.h"
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* createList(int a[], int n);
struct ListNode* sortList(struct ListNode* head);
void output(struct ListNode* head);
struct ListNode* insertNode(struct ListNode* head, int n);
struct ListNode* removeNode(struct ListNode* head, int n);
int main() {
int a[10000];
int n, ins, rm;
scanf("%d", &n);
scanf("%d", &ins);
scanf("%d", &rm);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
struct ListNode* list = createList(a, n);
output(list);
list = sortList(list);
output(list);
list = insertNode(list, ins);
output(list);
list = removeNode(list, rm);
output(list);
return 0;
}
struct ListNode* createList(int a[], int n) {
// TODO: 填写创建链表的函数
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
//先定义一个头指针
head->next = NULL;
head->val = a[0];
struct ListNode* current = head;
for (int i = 1; i < n; i++)
{
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
current->next = newnode;
newnode->next = NULL;
newnode->val = a[i];
current = current->next;
}
return head;
}
struct ListNode* sortList(struct ListNode* head) {
// TODO: 填写链表排序的函数
if (head == NULL || head->next == NULL)
{
return head;
}
int temp;
struct ListNode* current;
struct ListNode* tail=NULL;
int num;
do {
num = 0;
current = head;
while (current->next!=tail) {
if (current->val > current->next->val)
{
temp = current->next->val;
current->next->val = current->val;
current->val = temp;
num = 1;
}
current = current->next;
}
tail = current;
}
while (num);
return head;
}
void output(struct ListNode* head) {
// TODO: 填写输出每个节点值的函数
struct ListNode* current = head;
while (current != NULL)
{
printf("%d\n", current->val);
current = current->next;
}
}
struct ListNode* insertNode(struct ListNode* head, int n) {
//完成前插
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* current = head;
newnode->val = n;
newnode->next = NULL;
if (head == NULL || n < head->val)
{
newnode->next = head;
return newnode;
}
//接下来进行后插
while(current->next!=NULL&¤t->next->val<n)
{
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
return head;
}
struct ListNode* removeNode(struct ListNode* head, int n) {
// TODO: 填写删除链表中指定值的函数
struct ListNode* current = head;
//第一个就是
if (head->val == n)
{
return head->next;
}
//第二个就是
if (head->next!=NULL && head->next->val == n)
{
head->next = head->next->next;
return head;
}
//后面才是的话
while (current->next != NULL && current->next->val!=n)
{
current = current->next;
}
if (current->next == NULL) {
return head;
}
current->next = current->next->next;
return head;
}
链表的基础操作
于 2023-12-03 13:11:39 首次发布