概念区分:
头结点和头指针
通常使用头指针来标识一个链表,如单链表L,头指针为NULL
时表示一个空表。
为了操作上的方便,在单链表第一个节点之前添加一个头结点。头结点的额指针域指向线性表的第一个元素节点。
不管带不带头结点,头指针总是指向链表的第一个节点。头结点是带头结点链表的第一个节点。
基本操作
创建链表
链表长度
查找元素
插入数据
删除数据
- 创建链表
//2020/4/4
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
node* next;
}Node;
//建立含有头结点的链表
Node* create(int A[])
{
Node *head,*p,*s;//head头指针、p、q用于表示关系,s表示新建节点
head = (Node*)malloc(sizeof(Node));
head->next = NULL;
p = head;
for(int i = 0;i<8;i++)//尾插法
{
s = (Node*)malloc(sizeof(Node));
s->data = A[i];
s->next = NULL;
p->next = s;
p = s;
}
return head;
}
int find(Node* head,int x)
{
int count = 0;
Node *p;
p = head->next;
while(p)
{
if(p->data == x)
count++;
p = p->next;
}
return count;
}
void insert_pos(Node *head,int pos,int x)
{
int i;
Node *p,*s;
p = head;
for(i = 0;i<pos-1;i++)//寻找插入位置的前一个元素
{
p = p->next;
}
s = (Node*)malloc(sizeof(Node));
s->data = x;
s->next = p->next;
p->next = s;
}
void insert_head(Node *head,int x)
{
Node *p,*s;
p = head;
s = (Node*)malloc(sizeof(Node));
s->data = x;
s->next = p->next;
p->next = s;
}
void insert_rear(Node* head,int x)
{
Node *p,*s;
p = head;
while(p)
{
if(p->next == NULL)
break;
else p = p->next;
}
s = (Node*)malloc(sizeof(Node));
s->data = x;
s->next = NULL;
p->next = s;
}
void del_one(Node* head,int x)
{
Node *p,*q;
p = head->next;//指向第一个元素节点
q = head;
while(p)
{
if(p->data == x)
{
q->next = p->next;
free(p);
break;
}
else
{
q = p;
p = p->next;
}
}
}
void del_all(Node* head,int x)
{
Node *p,*q;
p = head->next;
q = head;
while(p)
{
if(p->data == x)
{
q->next = p->next;
free(p);
p = q->next;
}
else
{
q = p;
p = p->next;
}
}
}
int isEmpty(Node* head)
{
if(head->next == NULL)
return 1;
else return 0;
}
int len(Node *head)
{
int count = 0;
Node* p =head->next;
while(p)
{
count++;
p = p->next;
}
return count;
}
void print(Node* head)
{
Node *p;
p = head->next;
while(p)
{
if(p->next == NULL)
printf("%d\n",p->data);
else printf("%d ",p->data);
p = p->next;
}
}
int main()
{
int A[8] = {1,2,3,4,5,6,7,7};
Node* head = create(A);
print(head);
insert_pos(head,8,1);
print(head);
insert_head(head,7);
print(head);
insert_rear(head,1);
print(head);
del_one(head,1);
print(head);
del_all(head,1);
print(head);
printf("%d\n",isEmpty(head));
printf("%d\n",len(head));
return 0;
}