include<stdio.h>
include<string.h>
include<malloc.h>
include<stdlib.h>
define ERROR - 2
define OK 1
define OVERFLOW - 1
define LIST_INIT_SIZE 100
define LISTINCREASE 10
//鏈表的實現
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
//構造一個鏈表
int InitList(LinkList L)//用指向指針的形參,可以解決局部變量未初始化的問題,但不知道為什么可以解決(參數有個星號,但是顯示不出來)
{
L = (LNode)malloc(sizeof(LNode));//L前面有個星號,第一個LNode后面要加一個星號
if (!(L)) exit(OVERFLOW);//L前面有個星號,在括號里面
(*L)->next = NULL;//建立了頭結點
return OK;
}
//用頭插法插入數據
void HeadInsert(LinkList L)
{
int num;
while (scanf_s("%d", &num) != EOF)
{
LNode temp;
temp = (LNode)malloc(sizeof(LNode));
if (!temp) exit(OVERFLOW);
temp->data = num;
temp->next = L->next;
L->next = temp;
}
}
//用尾插法插入數據
//void RearInsert(LinkList *L)
//{
// int num;
// LNode rear = (L);
// while (scanf_s("%d", &num) != EOF)
// {
// LNode temp;
// temp = (LNode)malloc(sizeof(LNode));
// temp->data = num;
// temp->next = NULL;
// rear->next = temp;
// rear = temp;
// }
//}
void RearInsert(LinkList L)//用的一級指針,和用二級指針的運行結果一樣(不明白為什么?)
{
int num;
LNode *rear = L;
while (scanf_s("%d", &num) != EOF)
{
LNode temp;
temp = (LNode)malloc(sizeof(LNode));
if (!temp) exit(OVERFLOW);
temp->data = num;
temp->next = NULL;
rear->next = temp;
rear = temp;
}
}
//輸出鏈表中的所有元素
void PrintList(LinkList L)
{
LNode *temp = L->next;
int j = 0;
while (temp)
{
if (j == 0) printf("%d", temp->data);
else printf(" %d", temp->data);
temp = temp->next;
j++;
}
}
//鏈表任意位置的插入
int ListInsert(LinkList L, int i, int e)//插入在鏈表的第i個位置
{
int num = 0;//計數器
LNode *temp = L;
while (temp && (num < i - 1))//插入時要找第i個元素之前的一個元素
{
temp = temp->next;
num++;
}
if (!temp || num > i - 1)// i < 1或者 i大於鏈表長度加1
return ERROR;
LNode temp1;
temp1 = (LNode)malloc(sizeof(LNode));
temp1->data = e;
temp1->next = temp->next;
temp->next = temp1;
return OK;
}
//鏈表元素的刪除
int ListDelet(LinkList L, int i)
{
if (L->next == NULL) return ERROR;//要刪除元素之前要先檢查是否有元素可刪
int num = 0;//計數器
LNode *temp = L;
while (!temp && (num < i - 1))
{
temp = temp->next;
temp++;
}
if ((!temp->next) || (num > i - 1)) return ERROR;
LNode *temp1;
temp1 = temp->next;
temp->next = temp->next->next;
free(temp1);
return OK;
}
//鏈表的清空
void ClearList(LinkList L)//頭結點保存,其他結點釋放
{
LNode *temp = L->next;
while (temp)
{
LNode *temp1 = temp->next;
free(temp);
temp = temp1;
}
}
//鏈表的銷毀
void DestroyList(LinkList L)
{
LNode *temp = L;
while (L)
{
L = L->next;
free(temp);
temp = L;
}
}
int main()
{
LinkList p;
InitList(&p);
//HeadInsert(p);
RearInsert(p);
ListInsert(p, 2, 10);
ListDelet(p, 1);
PrintList(p);
ClearList(p);
printf("銷毀完畢\n");
}