解题思路:
注意事项:
参考代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* creatlist()
{
struct Node* headnode = (struct Node*)malloc(sizeof(struct Node));
headnode->next = NULL;
return headnode;
}
struct Node* creatnode(int data)
{
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
void printlist(struct Node* head)
{
struct Node* pmove = head->next;
if (pmove == NULL)
printf("Link list is empty\n");
while (pmove)
{
printf("%d ", pmove->data);
pmove = pmove->next;
if(!pmove)
printf("\n");
}
}
void insertneed(struct Node* head, int a, int b)
{
int cnt = 1,i;
struct Node* newnode = creatnode(b);
struct Node* postnodeFront = head;
struct Node* posnode = head->next;
if (!posnode&&a>1)
{
printf("insert fail\n");
return;
}
if (a < 1)
{
printf("insert fail\n");
return;
}
while (cnt != a)
{
postnodeFront = posnode;
if (posnode == NULL)
return;
posnode = posnode->next;
cnt++;
}
if (a > cnt)
{
printf("insert fail\n");
return;
}
postnodeFront->next = newnode;
newnode->next = posnode;
printf("insert OK\n");
}
void deletenode(struct Node* head, int data)
{
int cnt = 1;
struct Node* postnodeFront = head;
struct Node* postnode = head->next;
if (postnode == NULL)
{
printf("delete fail\n");
return;
}
while (cnt != data)
{
postnodeFront = postnode;
postnode = postnodeFront->next;
cnt++;
}
if (cnt == data)
{
postnodeFront->next = postnode->next;
printf("delete OK\n");
}
else
{
printf("delete fail\n");
return;
}
}
void getlist(struct Node* head1, int data)
{
struct Node* posnode = head1->next;
int cnt = 1;
if (posnode == NULL)
{
printf("get fail\n");
}
else if (data == 1)
printf("%d\n", posnode->data);
while (cnt!=data)
{
cnt++;
posnode = posnode->next;
if (posnode == NULL)
{
printf("get fail\n");
break;
}
if (cnt == data)
printf("%d\n", posnode->data);
}
}
void insertheadby(struct Node* head, int data)
{
struct Node* newNode = creatnode(data);
if (head->next ==NULL)
head->next = newNode;
else
{
newNode->next = head->next;
head->next = newNode;
}
}
int main()
{
struct Node* head1 = creatlist();
int n,i,data,num1,num2;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &data);
insertheadby(head1, data);
}
scanf("%d", &n);
char str[100];
for (int i = 0; i < n; i++)
{
scanf("%s", &str);
if (!strcmp(str, "show"))
{
printlist(head1);
continue;
}
if (!strcmp(str, "delete"))
{
scanf("%d", &num1);
deletenode(head1, num1);
continue;
}
if (!strcmp(str, "insert"))
{
scanf("%d%d", &num1, &num2);
insertneed(head1, num1, num2);
continue;
}
if (!strcmp(str, "get"))
{
scanf("%d", &num1);
getlist(head1, num1);
continue;
}
}
return 0;
}
0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复