6-7 頭插法創建單鏈表(C) (25 分)
本題要求實現兩個函數,輸入n個數據,採用頭插法創建單鏈表並打印。例如:如果輸入4 ,再輸入3 7 9 5,則應打印輸出5 9 7 3。
鏈表結點結構定義:
struct Node { //鏈表結點
int data; //數據
struct Node* link; //指向下一個結點的指針
};
函數接口定義:
/* 頭插法建立單鏈表:返回單鏈表的頭指針 */
struct Node* buildLinkedList(int* arr, int n); /* 頭插法建立單鏈表 */
void printLinkedList(struct Node* head); /* 打印鏈表 */
其中arr
和n
是用戶傳入的參數,n
的值不超過100000。head
爲單鏈表的頭指針。
裁判測試程序樣例:
#include <stdio.h>
#include <stdlib.h>//malloc函數
struct Node { //鏈表結點
int data; //數據
struct Node* link; //指向下一個結點的指針
};
/* 頭插法建立單鏈表:返回單鏈表的頭指針 */
struct Node* buildLinkedList(int* arr, int n); /* 頭插法建立單鏈表 */
void printLinkedList(struct Node* head); /* 打印鏈表 */
int main(int argc, char const *argv[]) {
int n, i;
int* a;
scanf("%d", &n);
a = (int*)malloc(n * sizeof(int)); //動態內存分配申請數組空間
for (i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
struct Node* head = NULL; //聲明一個指針變量head
//創建鏈表,把返回的頭指針賦值給head指針變量
head = buildLinkedList(a, n);
//打印鏈表:整個鏈表用head來代表。
printLinkedList(head);
free(a); //釋放存儲空間
return 0;
}
/* 請在這裏填寫答案 */
輸入樣例:
輸入包含兩行。 第一行爲數據個數n,不超過100000。 第二行爲n個空格分隔的整數,其值不超過int值的範圍。
4
3 7 9 5
輸出樣例:
在一行輸出鏈表每個結點中的數據,以空格分隔,但行尾無多餘空格。
5 9 7 3
struct Node * buildLinkedList(int* arr, int n){
struct Node *head,*op;
head=(struct Node*)malloc(sizeof(struct Node));
head->link =NULL;
for(int i=0;i<n;i++){
op=(struct Node*)malloc(sizeof(struct Node));
op->data =arr[i];
op->link=head->link;
head->link=op;
}
return head;
}