//不带头节点的单链表
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int ElemType;
typedef struct Node{
ElemType data;
struct Node* next;
}Node,*plist;
//初始化
void init(plist *phead){
*phead=NULL;
}
Node* buyNode(ElemType val)
{
Node* pnewnode = (Node*)malloc(sizeof(Node));
pnewnode->data = val;
pnewnode->next = NULL;
return pnewnode; //第一次调用的时候就是创建首元节点
}
//头插法
int insertHead(plist* phead,ElemType val){
Node* pnewnode=buyNode(val);
pnewnode->next=(*phead);
(*phead)=pnewnode;
return 0;
}
//尾插法
int insertTail(plist* ptwohead,ElemType val){
Node* pnewnode=buyNode(val);
Node* ptail=*ptwohead;
if(*ptwohead==NULL){
(*ptwohead)=pnewnode;
}
while(ptail->next!=NULL){
ptail=ptail->next;
}
ptail->next=pnewnode;
return 1;
}
void print(Node* head){
Node* n=head;
while(n!=NULL){
printf("%d ",n->data);
n=n->next;
}
printf("\n");
}
bool empty(Node* phead)
{
return phead==NULL?true:false;
}
int deleteHead(plist* phead){
if(empty(*phead)){
return 0;
}
Node* n=*phead;
*phead=n->next;
free(n);
return 1;
}
int deleteTail(plist* phead){
if(empty(*phead)){
return 0; // 链表为空,返回0表示没有删除操作
}
Node* pfront = *phead;
Node* pprev = NULL; // 记录链表的倒数第二个节点
Node* pcur = pfront;
// 遍历链表直到倒数第二个节点
while(pcur->next != NULL){
pprev = pcur;
pcur = pcur->next;
}
// 如果链表中只有一个节点,那么pprev将仍然是NULL
if(pprev == NULL){
// 链表只有一个节点,直接删除头节点并释放内存
free(*phead);
*phead = NULL;
} else {
// 链表有多个节点,删除尾节点并释放内存
free(pcur);
pprev->next = NULL; // 将倒数第二个节点的next指针设为NULL
}
return 1; // 成功删除尾节点,返回1
}
bool destory(plist* phead){
Node* p1=*phead;
Node* pnext=NULL;
while(p1!=NULL){
pnext=p1->next;
free(p1);
p1=pnext;
}
*phead=NULL;
return true;
}
int main() {
Node* head = NULL;
init(&head);
int val;
scanf("%d",&val);
head= buyNode(val);
int n;
scanf("%d",&n); //输入要插入的值
if(insertHead(&head,n)==0){
printf("插入成功!\n");
print(head);
}
int m;
scanf("%d",&m);
if(insertTail(&head,m)==1){
printf("插入成功!\n");
print(head);
}
//删除头部元素
if(deleteHead(&head)){
printf("成功删除头部元素!\n");
print(head);
}
if(deleteTail(&head)){
printf("成功删除尾部元素!\n");
print(head);
}
if(destory(&head)){
printf("销毁成功!\n");
}
return 0;
}
不带头节点的相关操作
最新推荐文章于 2024-10-08 14:26:15 发布