#include<stdio.h>
#include<malloc.h>
typedef int DateType;
typedef struct node {
DateType date;
struct node *next;
}ListNode;
int CreatList(ListNode *head) {
ListNode *p;
p = head;
DateType x;
int n,i;
printf("请输入创建节点个数\n");
scanf("%d",&n);
printf("请输入值: ");
for(i=0; i<n; i++) {
scanf("%d",&x);
ListNode *s = (ListNode*)malloc(sizeof(ListNode));
if(!s) {
printf("空间申请失败!\n");
return 0;
}
s->date = x;
p->next = s;
p = s;
}
p->next = NULL;
return 1;
}
void DisPlay(ListNode *head) {
ListNode *p;
p = head->next;
if(p == NULL) {
printf("空链表!\n");
return;
}
printf("打印链表喽!\n");
while(p != NULL) {
printf("%d ",p->date);
p = p->next;
}
printf("\n");
return;
}
int Insert(ListNode *head,int k,DateType x) {
ListNode *p = head;
if(p->next == NULL) {
printf("空链表!\n");
return 0;
}
int i=0;
while(p != NULL && i<k) {
p = p->next;
i++;
}
if(i == k) {
ListNode *s = (ListNode*)malloc(sizeof(ListNode));
if(!s) {
return 0;
}
s->date = x;
s->next = p->next;
p->next = s;
return 1;
}
else {
printf("插入位置错误!\n");
return 0;
}
}
int Dele(ListNode *head,int k) {
ListNode *p = head;
if(p->next == NULL) {
printf("空链表!\n");
return 0;
}
int i=0;
while(p != NULL && i<k) {
p = p->next;
i++;
}
if(!p || !p->next) {
printf("删除位置错误!\n");
return 0;
}
ListNode *s = p->next;
p->next = s->next;
free(s);
return 1;
}
int main() {
ListNode *head = (ListNode*)malloc(sizeof(ListNode));
if(head == NULL) {
printf("申请空间失败!");
}
if(CreatList(head)) {
printf("创建成功啦!\n");
DisPlay(head);
}
int k; DateType x;
printf("输入将插入位置和值:\n");
scanf("%d %d",&k,&x);
if(Insert(head,k-1,x)) {
printf("插入成功!\n");
DisPlay(head);
}
printf("输入将删除位置:\n");
scanf("%d",&k);
if(Dele(head,k-1)) {
printf("删除成功!\n");
DisPlay(head);
}
return 0;
}