码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-11-10 11:57:26      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:lib   let   str   turn   type   --   eof   scanf   scan   

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

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

标签:lib   let   str   turn   type   --   eof   scanf   scan   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!