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

#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\n");
return head;
}
head = node;
printf("success\n");
return head;
}
if (index == 0) {
node->next = head;
head = node;
printf("success\n");
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\n");
}
if(count != index-1){
printf("failed\n");
}

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;
}

posted @ 2019-11-10 10:59  马猴烧酒孟优秀  阅读(304)  评论(0编辑  收藏  举报