【计蒜课】【数据结构】【链表的创建、插入、遍历操作的复习】

#include <stdio.h>
#include <stdlib.h>

typedef struct Node{
int data;
struct Node *next;

}Node, *LinkedList;

LinkedList insert(LinkedList head, Node *node, int index) {
if (head == NULL) {
if (index != 0) {
printf("failed ");
return head;
}
head = node;
printf("success ");
return head;
}
if (index == 0) {
node->next = head;
head = node;
printf("success ");
return head;
}
Node *current_node = head;
int count = 0;
while (current_node->next != NULL && count < index - 1) {
current_node = current_node->next;
count++;
}
if (count == index - 1) {
node->next = current_node->next;
current_node->next = node;
printf("success ");
}
if(count != index-1){
printf("failed ");
}

return head;
}

void output(LinkedList head) {
if(head == NULL){
return;
}
Node *current_node=head;
while(current_node->next != NULL){
printf("%d ",current_node->data);
current_node=current_node->next;
}
printf("%d",current_node->data);

}

void clear(LinkedList head) {
Node *current_node = head;
while (current_node != NULL) {
Node *delete_node = current_node;
current_node = current_node->next;
free(delete_node);
}
}

int main() {
LinkedList linkedlist = NULL;
int n;
scanf("%d",&n);
while(n>=1 && n<=100){
int p;
int q;
scanf("%d %d",&p,&q);
Node *node=(Node*)malloc(sizeof(Node));
node->data=q;
node->next=NULL;
linkedlist=insert(linkedlist,node,p);
n--;
}
output(linkedlist);
clear(linkedlist);
return 0;
}

原文地址:https://www.cnblogs.com/P201821430045/p/11829166.html