#include<stdio.h>
#include<malloc.h>
typedef int DataType; //定義線性表的數據類型 假設爲int型
typedef struct Node //定義單鏈表的節點類型
{
DataType data;
struct Node *next;
} Node;
Node *CreatList(DataType a[],int n)
{
Node *s = NULL;
Node *first = (Node *)malloc(sizeof(Node));
first->next = NULL; //初始化節點
for (int i = 0; i < n; i++)
{
s = (Node *)malloc(sizeof(Node));
s -> data = a[i]; //爲每個數組元素建立一個節點
s -> next = first -> next; first ->next = s; //將節點s插入到頭結點 之後
}
return first;
}
void PrintList(Node *first)
{
Node *p = first -> next; //工作指針p初始化
while (p != NULL)
{
printf("%d", p -> data); //輸出節點的數據域 假設爲int型
p = p -> next; //工作指針p後移,注意不能寫作p++
}
printf("\n");
}
int Length(Node *first)
{
Node *p = first -> next; //工作指針p初始化
int count = 0; //累加器count初始化
while (p != NULL)
{
p = p -> next;
count++;
}
return count;
}
int Insert (Node *first,int i, DataType x)
{
Node *s = NULL, *p = first; //工作指針後移
int count = 0;
while ( p != NULL && count < i -1)
{
p = p -> next;
count ++;
}
if(p == NULL) { printf("位置錯誤,插入失敗\n"); return 0; }
else {
s = (Node *)malloc(sizeof(Node));
s -> data = x;
s -> next = p ->next = s;
return 1;
}
}
int main()
{
int r[5] = {1, 2, 3, 4, 5}, i, x;
Node *first = NULL;
first = CreatList(r, 5);
printf("當前線性表的數據爲:");
PrintList(first); //輸出當前鏈表 1 2 3 4 5
Insert(first, 2, 8); //在第二個位置插入值爲8的節點
printf("執行插入操作後數據爲:");
PrintList(first); //輸出輸入後鏈表1 8 2 3 4 5
printf("當前單鏈表的長度爲:%d\n", Length(first));
getchar(); getchar();
return 0;
}