初学者在学习链表时一般不明白链表操作的原理和方法,因此对链表常常感到困惑不解,在这里我给大家分享一下链表的基本操作方法,希望对大家有所帮助。
链表的基本操作包括节点的插入、删除、修改、查找,以及链表的逆序、输出等。
首先我们声明一个结构体作为链表的节点类型。
#include<stdio.h>
#include<malloc.h>
struct node
{
int num;
struct node *next;
};
函数声明:
void InsertHead(struct node **pphead,int val); //头插
void InsertTail(struct node **pphead,int val); //尾差
void DeleteHead(struct node **pphead); //头删
void DeleteTail(struct node **pphead); //尾删
void Display(struct node *phead); //输出
void reverse(struct node **head); //逆序
void main() //主函数
{
struct node *head=NULL;
InsertTail(&head,3);
InsertHead(&head,1);
InsertHead(&head,2);
DeleteHead(&head);
DeleteTail(&head);
Display(head);
}
/*****************************函数体*****************************************/
//头插的原理是将每一个节点插入到链表的前面
void InsertHead(struct node **pphead,int val)
{
//申请一个节点空间
struct node *p=(struct node *)malloc(sizeof(struct node));
p->num=val;
p->next=*pphead; //将其插入到头节点的前面
*pphead=p;
}
//尾插的原理与头插正好相反,就是将要插入的节点插入链表的末尾
void InsertTail(struct node **pphead,int val)
{
struct node *q=*pphead;
struct node *p=(struct node *)malloc(sizeof(struct node));
p->num=val;
p->next=NULL;
if(*pphead==NULL) //如果链表为空,将该节点作为头节点
{
*pphead=p;
}
else
{
while(q->next!=NULL) //找到链表最后一个节点
q=q->next; //插入
q->next=p;
}
}
//链表输出
void Display(struct node *phead)
{
struct node *p=phead;
while(p!=NULL) //链表不为空
{
printf("%d\n",p->num); //输出
p=p->next;
}
}
void DeleteHead(struct node **pphead)
{
struct node *p=*pphead;
if(*pphead==NULL) //如果链表为空,返回
return;
else
{
*pphead=(*pphead)->next; //删除头节点
free(p); //释放删除的节点空间
p=NULL;
}
}
void DeleteTail(struct node **pphead)
{
struct node *p=*pphead;
if(*pphead==NULL) //如果链表为空,返回
return;
else if(p->next==NULL) //链表只有一个节点
{
free(*pphead); //释放该节点
*pphead=NULL; //链表置空
}
else
{
while(p->next->next!=NULL) //寻找最后一个节点
{
p=p->next;
}
free(p->next); //删除最后一个节点
p->next=NULL; //最后一个节点next置空
}
}
void reverse(struct node **head) //链表逆序
{
struct node *p,*s;
p=*head;
if((*head)==NULL) //如果链表为空,返回
return;
else if((*head)->next==NULL) //如果链表仅有一个节点,返回
return;
else
{
s=(*head)->next;
reverse(&s); //通过递归找到最后一个节点s
p->next->next=p; //头节点变为为节点
s->next=p; //用头插的方法将链表逆序
p->next=NULL;
(*head)=s; //是头节指向新的链表
}
}