/*
链表创建
链表遍历
节点追加
节点查找
节点插入
节点删除
*/
# include <stdio.h>
# include <malloc.h>
struct Node
{
int data;
struct Node * pNext;
};
void create_list(struct Node * pHead)
{
int len;
int count = 0;
pHead->pNext = NULL;
printf("请输入节点个数:");
scanf("%d", &len);
for (int i = 0; i < len; i++)
{
struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
pHead->pNext = pNew;
if (i > 20 && i < 60)
{
pNew->data = i - (count += 2);
}
else if (i >= 60)
{
pNew->data = i - 78;
}
else
{
pNew->data = i;
}
pNew->pNext = NULL;
pHead = pNew;
}
}
void traverse_list(struct Node * pHead)
{
while (pHead)
{
printf("%d\n", pHead->pNext->data);
pHead = pHead->pNext;
}
}
void append_list(struct Node * pHead)
{
int count;
int s = 0;
printf("请输入追加节点数:");
scanf("%d", &count);
while (pHead->pNext)
{
pHead = pHead->pNext;
s++;
}
for (int i = 0; i < count; i++)
{
struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
pHead->pNext = pNew;
pNew->data = s++;
pNew->pNext = NULL;
pHead = pNew;
}
}
void insert_list(struct Node * pHead)
{
int n, num;
struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
struct Node * pTemp = (struct Node *)malloc(sizeof(struct Node));
printf("请输入你要在第几个节点后面插入:");
scanf("%d", &n);
printf("请输入你要插入的数据:");
scanf("%d", &num);
for (int i = 0; i < n; i++)
{
pHead = pHead->pNext;
if (!pHead)
{
printf("链表目前没那么多节点!!\n");
return;
}
}
pTemp = pHead->pNext;
pHead->pNext = pNew;
pNew->data = num;
pNew->pNext = pTemp;
}
void delete_list(struct Node * pHead)
{
int n;
struct Node * pTemp = (struct Node *)malloc(sizeof(struct Node));
printf("要删除第几个节点:");
scanf("%d", &n);
for (int i = 0; i < n - 1; i++)
{
pHead = pHead->pNext;
if (!pHead)
{
printf("链表目前没那么多节点!!\n");
return;
}
}
pTemp = pHead->pNext->pNext;
free(pHead->pNext);
pHead->pNext = pTemp;
}
void contains(struct Node * pHead)
{
int d;
int c = 0;
int i = 0;
printf("请输入要查找的数据:");
scanf("%d", &d);
while (pHead->pNext)
{
i++;
if (pHead->pNext->data == d)
{
c = 1;
printf("第%d个元素的值为%d\n", i, d);
}
pHead = pHead->pNext;
}
if (0 == c)
{
printf("链表中不存在%d!\n", d);
}
}
int main(void)
{
struct Node * pHead = (struct Node *)malloc(sizeof(struct Node));
pHead->pNext = NULL;
create_list(pHead);
//contains(pHead);
//append_list(pHead);
//insert_list(pHead);
//delete_list(pHead);
//traverse_list(pHead);
return 0;
}