单链表
1.设计节点:
struct Node{
int data;
struct Node *next;
};
2.创建节点
//1.创建节点
struct Node *create(int data){
struct Node *node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
3.插入数据
//2.插入数据
bool insert(struct Node *head, struct Node* new)
{
if(head == NULL || new == NULL) return false;
new->next = head->next;
head->next = new;
return true;}
4.遍历链表
//3.遍历链表
void display(struct Node *head)
{
if(head==NULL || head->next==NULL) return ; //链表上没有数据
head = head->next;
while(head)
{
printf("%d ", head->data);
head = head->next;
}printf("\n");
}
5.删除节点
4.删除节点
//4.删除节点
bool delete(struct Node* head, int data)
{
//判断链表
if(head==NULL || head->next == NULL) return false;
//查找data这个数据所在节点的上一个节点
while(head->next != NULL)
{
if(head->next->data == data)
{
//定义遍历保存要删除的节点
struct Node* p = head->next;
head->next = p->next;
p->next = NULL;
free(p);
break;
}else head = head->next;
}
return true;
}
6.尾插入
bool insert_tail(struct Node* head, struct Node* new)
{
if(head == NULL || new == NULL) return false;
//遍历到链表尾部
struct Node * p = head;
while(p->next){
p = p->next;
}
p->next = new;
return true;
}