目录
一、什么是链表
链表是一种数据结构,即数据存放的思想。
链表与数组相似。
数组的缺点:增、删、改、查(不灵活)。空间大小确定
链表的每一项都是一个结构体。
二、链表的基础表达
struct Test
{
Int data;
struct Test *next;
}
三、链表静态添加和动态遍历
动态添加:
void printlink(struct Test *head)
{
struct Test *point;
point = head;
while (1){
if(point != NULL){
printf("%d ",point->data);
point = point->next;
}else{
putchar('\n');
break;
}
}
}
四、链表的查询
int searchLinkNum(struct Test *head,int data)
{
while (head != NULL){
if(head->data == data){
return 1;
}
head = head->next;
}
return 0;
}
五、链表的插入
-
节点前插入
(1)从第一个节点插入
(2)从其他节点插入
struct Test *insertFromFront(struct Test *head,int data,struct Test *new)
{
struct Test *p = head;
if(p->data == data){
new->next = head;
return new;
}
while(p->next != NULL){
if(p->next->data == data){
new->next = p->next;
p->next = new;
return head;
}
p = p->next;
}
return head;
}
-
节点后插入
找到目标节点
new->nextx = 目标节点->next;
目标节点->next = &new;
Ag:
int insertFromBhind(struct Test *head,int data,struct Test *new)
{
struct Test *p;
p = head;
while(p != NULL){
if(p->data == data){
new->next = p->next;
p->next = new;
return 1;
}
p = p->next;
}
return 0;
}
六、链表的删除
(1)删除第一个节点
(2)删除其他节点
struct Test *deleteLink(struct Test *head,int data)
{
struct Test *p = head;
if(p->data == data){
head = p->next;
return head;
}
while(p->next != NULL){
if(p->next->data == data){
p->next = p->next->next;
p->next->next = NULL;
return head;
}
}
return head;
}
七、链表的动态插入
-
头插法
struct Test *insertFromHead(struct Test *head,struct Test *new)
{
if(head == NULL){
head = new;
}else{
new->next = head;
head = new;
}
return head;
}
struct Test *creatLink(struct Test *head)
{
struct Test *new;
while(1){
new = (struct Test *)malloc(sizeof(struct Test));
printf("input your new node data:\n");
scanf("%d",&(new->data));
if(new->data == 0){
printf("quit!\n");
return head;
}
head = insertFromHead(head,new);
}
}
-
尾插法
struct Test *insertBhind(struct Test *head,struct Test *new)
{
struct Test *p = head;
if(p == NULL){
head = new;
return head;
}
while(p->next != NULL){
p = p->next;
}
p->next = new;
return head;
}
struct Test *creatLink2(struct Test *head)
{
struct Test *new;
while(1){
new = (struct Test *)malloc(sizeof(struct Test));
printf("input your new node data:\n");
scanf("%d",&(new->data));
if(new->data == 0){
printf("quit!\n");
return head;
}
head = insertBhind(head,new);
}
}