先上代码
结构体
#include <stdio.h>
#include <stdlib.h>
typedef struct nodeList {
int data; //数据域
struct nodeList *next; //指针域
} nodeList;
遍历链表
//遍历链表
void TraverseList(struct nodeList *head)
{
while(head != NULL){
printf("%d \n",head->data);
head=head->next;
}
}
头插法
void HeadCreatList(struct nodeList *head, int n)
{
struct nodeList *node;
for (int i = 0; i < n; ++i)
{
node=(struct nodeList *)malloc(sizeof(struct nodeList));
node->data = i;
node->next = head->next;
head->next = node;
}
head->data = n;
}
头插法,新结点始终在头结点之后,核心在于:
node->data = i;
node->next = head->next;
head->next = node;
尾插法
void TailCreatList(struct nodeList *head, int n)
{
struct nodeList *node,*end;
end = head;
for (int i = 0; i < n; ++i)
{
node=(struct nodeList *)malloc(sizeof(struct nodeList));
node->data = i;
end->next = node;
end = node;
}
head->data = n;
}
尾插法,新结点始终在尾结点之后,核心在于:
node->data = i;
end->next = node;
end = node;
删除某个值
void deleteFromList(struct nodeList *head, int target)
{
struct nodeList *pre,*tmp;
int count=0;
tmp = head;
pre = head;
head= head->next;
while(head != NULL){
if (head->data == target){
pre->next = head->next;
free(head);
count--;
}else{
pre = head;
count++;
}
head= head->next;
}
tmp->data = count;
head = tmp;
}
实测:
int main()
{
struct nodeList *head,*node;
head=(struct nodeList *)malloc(sizeof(struct nodeList));
//头结点
//head->data = NULL;
head->next = NULL;
//头插法
HeadCreatList(head, 5);
printf("头插法: \n");
TraverseList(head);
//尾插法
head->next = NULL;
TailCreatList(head, 5);
printf("尾插法: \n");
TraverseList(head);
//删除
deleteFromList(head,2);
printf("删除2: \n");
TraverseList(head);
free(head);
head = NULL;
return 0;
}
执行结果:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。