思路
设计一个 Insert(int data,int n) 函数,使得一个存有该数据的节点能够插入第n个位置。
代码实现
设计一个 Insert 函数,一个 Print 函数 以及 main 函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #include<stdio.h> #include<stdlib.h> struct Node{ int data; struct Node* next; }; struct Node* head; void Insert (int data,int n){ struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node)); temp1->data = data; temp1->next = NULL; if(n==1){ temp1->next = head; head = temp1; return; } struct Node* temp2 = head; for(int i=0;i<n-2;i++){ temp2 = temp2->next; } temp1->next = temp2->next; temp2->next = temp1; } void Print(){ struct Node* temp = head; while(temp != NULL){ printf("%d ",temp->data); temp = temp->next; } printf("\n"); } int main(){ head = NULL; printf("How many numbers?\n"); int n,i,number,position; scanf("%d",&n); for(i=0;i<n;i++){ printf("Enter the number and position\n"); scanf("%d%d",&number,&position); Insert(number,position); Print(); } return 0; }
|