#include"List.h"voidListDestroy(Node** head){
Node* cur =*head;while(cur){*head = cur->next;free(cur);
cur =*head;}*head =NULL;}//打印//这里也不需要断言,因为空链表其实也是可以进行打印操作的voidListPrint(Node* head){
Node* cur = head;while(cur){printf("%d ", cur->data);
cur = cur->next;}printf("NULL\n");}
Node*BuyListNode(int data){
Node* pNewNode =(Node*)malloc(sizeof(Node));if(NULL== pNewNode){returnNULL;}
pNewNode->data = data;
pNewNode->next =NULL;return pNewNode;}//头插voidListPushFront(Node** head,int data){//head这里不用断言,因为head其实永远都不可能是空的assert(head);//链表为空head也不为空,因为head是头指针的地址,所以是需要断言的//*head不需要断言,因为链表为空的时候也是可以进行数据插入的
Node* pNewNode =BuyListNode(data);/*if (NULL == *head)
{
*head = pNewNode;
pNewNode->next = NULL;
}
else
{
pNewNode->next = *head;
*head= pNewNode;
}*/
pNewNode->next =*head;*head = pNewNode;}//尾插,在链表为空的前提下进行尾插,就一定要使用二级指针,因为在链表为空的情况下//进行尾插的时候,这个时候一定是会改变头指针的指向的,所以我们需要使用二级指针voidListPushBack(Node** head,int data){
Node* pNewNode =BuyListNode(data);if(NULL==*head){*head = pNewNode;}else{
Node* cur =*head;while(cur->next){
cur = cur->next;}
cur->next = pNewNode;}}//头删,和上面的思路一样,在进行头删的时候也需要传递二级指针voidListPopFront(Node** head){assert(head);assert(*head);//当链表为空的时候,不能头删,所以要断言if(NULL==*head){assert(*head);}elseif(NULL==(*head)->next){free(*head);*head =NULL;}else{
Node* cur =*head;*head =(*head)->next;free(cur);
cur =*head;}}//尾删voidListPopBack(Node** head){if(NULL==*head){assert(*head);}elseif(NULL==(*head)->next){free(*head);*head =NULL;}else{
Node* cur =*head;while(cur->next->next){
cur = cur->next;}free(cur->next);
cur->next =NULL;}}
Node*ListFind(Node* head,int data){//这里不用断言,因为空的链表也是可以进行查找的,所以是否为空其实是不影响的
Node* cur = head;while(cur){if(cur->data == data)return cur;
cur = cur->next;}returnNULL;}
main.c
#include"List.h"intmain(){
Node* p =NULL;ListPushFront(&p,10);ListPushFront(&p,20);ListPushFront(&p,30);ListPushFront(&p,40);ListPushFront(&p,50);ListPrint(p);ListPushBack(&p,1);ListPushBack(&p,2);ListPushBack(&p,3);ListPrint(p);ListPopBack(&p);ListPopBack(&p);ListPrint(p);ListPopFront(&p);ListPopFront(&p);ListPrint(p);//ListDestroy(&p);}
SList.h//不带头结点的单链表 //不带头结点的话,那么链表表中的第一个节点一顶存储的是有效元素#pragma once //保证头文件不被重复包含#include<assert.h>#include<stdlib.h>#include<stdio.h>//如果想要对链表进行操作,那么首先需要一个结点的结构体typedef i...